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

时间:2016-11-11 04:56:54

标签: c# .net wpf winforms

我正在尝试将图像附加到图像源但是在执行代码图像后却没有显示在我的页面中。

代码:

 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

3 个答案:

答案 0 :(得分:0)

解决此问题后,此问题的解决方案是:

调用函数获取BitmapImage并将其保存在照片变量中,如下所示:

"code-runner.executorMap": {
    "cpp": "g++ $fullFileName && ./a.out"
}

此函数将字节转换为BitmapImage

BitmapImage photo = byteToImage(byte[] buffer)

最后,将转换后的照片附加到像这样的图像源:

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

答案 1 :(得分:-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 :(得分:-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;