在WPF中使用Image控件来显示System.Drawing.Bitmap

Pra*_*dda 75 c# wpf

如何在WPF中BitmapImage控件分配内存中对象?

Lar*_*ens 86

根据http://khason.net/blog/how-to-use-systemdrawingbitmap-hbitmap-in-wpf/

   [DllImport("gdi32")]
   static extern int DeleteObject(IntPtr o);

   public static BitmapSource loadBitmap(System.Drawing.Bitmap source)
   {
       IntPtr ip = source.GetHbitmap();
       BitmapSource bs = null;
       try
       {
           bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, 
              IntPtr.Zero, Int32Rect.Empty, 
              System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
       }
       finally
       {
           DeleteObject(ip);
       }

       return bs;
   }
Run Code Online (Sandbox Code Playgroud)

它获取System.Drawing.Bitmap(来自WindowsBased)并将其转换为BitmapSource,它实际上可以用作WPF中Image控件的图像源.

image1.Source = YourUtilClass.loadBitmap(SomeBitmap);
Run Code Online (Sandbox Code Playgroud)

  • Thx Lars,但我做得更简单,BitmapImage bmpi = new BitmapImage(); bmpi.BeginInit(); bmpi.StreamSource = new MemoryStream(ByteArray); bmpi.EndInit(); image1.Source = bmpi; (7认同)
  • 大.您可以添加溶剂作为您自己问题的答案. (4认同)
  • 使用非托管句柄(例如HBITMAP)时,请考虑使用SafeHandles,请参阅http://stackoverflow.com/questions/1546091/wpf-createbitmapsourcefromhbitmap-memory-leak/7035036#7035036 (4认同)

小智 19

您可以使用图像的Source属性.试试这个代码......

ImageSource imageSource = new BitmapImage(new Uri("C:\\FileName.gif"));

image1.Source = imageSource;
Run Code Online (Sandbox Code Playgroud)

  • 他已经在内存中有位图,所以他不能使用uri (40认同)
  • 我有 Bitmap 对象,实际上它是从扫描设备生成的,所以我无法引用任何位置 (2认同)

Bad*_*boy 16

磁盘文件很容易,但内存中的Bitmap更难.

System.Drawing.Bitmap bmp;
Image image;
...
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();

image.Source = bi;
Run Code Online (Sandbox Code Playgroud)

偷了这里