2016-11-11 70 views
0

我试图将图像追加到图像源,但在执行代码图像后不会显示在我的页面中。在wpf中将图像追加到image.source

代码:

Bitmap bmp = (Bitmap)data.img; 
MemoryStream ms = new MemoryStream(); 
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png); 
ms.Position = 0; 
BitmapImage bi = new BitmapImage(); 
bi.BeginInit(); 
bi.StreamSource = ms; 
bi.EndInit(); 
imgPhoto.Source = bi; 

这是我要附加到imhPhoto.Source data.img规范。

this is data.img specifications

回答

0

解决此问题的工作后,对这个问题的解决办法是:

调用该函数以获取BitmapImage的,并保存照片的变量一样这个:

BitmapImage photo = byteToImage(byte[] buffer) 

这个函数将字节转换成BitmapImage

public BitmapImage byteToImage(byte[] buffer) 
{ 

using(var ms = new MemoryStream(buffer)) 
{ 
    var image = new BitmapImage(); 
    image.BeginInit(); 
    image.CacheOption = BitmapCacheOption.OnLoad; 
    image.StreamSource = ms; 
    image.EndInit(); 
} 

return image; 
} 

最后,附加变换的照片,以图象源是这样的:

imgPhoto.Source = photo; 
-2

你可以像这样指定路径。

//for App folder path 
      //var path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)+"\\Image\\pic.jpg"; 

      //for machine path 
      var path = @"C:\Users\User1\Pictures\pic.jpg"; 

      Bitmap bmp = new Bitmap(path); 
      MemoryStream ms = new MemoryStream(); 
      bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png); 
      ms.Position = 0; 
      BitmapImage bi = new BitmapImage(); 
      bi.BeginInit(); 
      bi.StreamSource = ms; 
      bi.EndInit(); 
      imgPhoto.Source = bi; 
-2

如果问题得以解决:

System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(@"g:\screenshot.png"); 

BitmapImage bi = new BitmapImage(); 
bi.BeginInit(); 

MemoryStream ms = new MemoryStream(); 
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); 
ms.Position = 0;    

bi.StreamSource = ms; 
bi.EndInit(); 

imgPhoto.Source = bi; 
+0

它说'imgPhoto.Source.Metadata投掷类型System.NotSupportedException的异常'和图像不显示尚未.. – Saif

+0

可以你看附图中的RawFormat?我认为这是主要问题,但我不知道如何让它知道格式 – Saif