简体   繁体   English

将图像附加到WPF中的image.source

[英]Append image to image.source in wpf

I am trying to append image to image source but after executing the code image is not displaying in my page. 我试图将图像追加到图像源,但是执行代码后图像未显示在页面中。

Code: 码:

 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;

this is data.img specifications that I want to append to imhPhoto.Source. 这是我要附加到imhPhoto.Source的data.img规范。

这是data.img规范

After working around this issue, the solution for this question is: 解决此问题后,此问题的解决方案是:

call the function to get BitmapImage and save it in photo variable like this: 调用该函数以获取BitmapImage并将其保存在photo变量中,如下所示:

BitmapImage photo = byteToImage(byte[] buffer)

this functionto convert byte to BitmapImage 此函数将字节转换为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;
}

finally, append converted photo to image source like this: 最后,将转换后的照片添加到图像源,如下所示:

imgPhoto.Source = photo;

You can assign path like this. 您可以这样分配路径。

  //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;

If this solves your problem : 如果这样可以解决您的问题:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM