WPF - converting Bitmap to ImageSource
For others, this works:
//If you get 'dllimport unknown'-, then add 'using System.Runtime.InteropServices;' [DllImport("gdi32.dll", EntryPoint = "DeleteObject")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DeleteObject([In] IntPtr hObject); public ImageSource ImageSourceFromBitmap(Bitmap bmp) { var handle = bmp.GetHbitmap(); try { return Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } finally { DeleteObject(handle); } }
For the benefit of searchers, I created a quick converter based on a this more detailed solution.
No problems so far.
using System;using System.Drawing;using System.IO;using System.Windows.Media.Imaging;namespace XYZ.Helpers{ public class ConvertBitmapToBitmapImage { /// <summary> /// Takes a bitmap and converts it to an image that can be handled by WPF ImageBrush /// </summary> /// <param name="src">A bitmap image</param> /// <returns>The image as a BitmapImage for WPF</returns> public BitmapImage Convert(Bitmap src) { MemoryStream ms = new MemoryStream(); ((System.Drawing.Bitmap)src).Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); BitmapImage image = new BitmapImage(); image.BeginInit(); ms.Seek(0, SeekOrigin.Begin); image.StreamSource = ms; image.EndInit(); return image; } }}
I do not believe that ImageSourceConverter
will convert from a System.Drawing.Bitmap
. However, you can use the following:
public static BitmapSource CreateBitmapSourceFromGdiBitmap(Bitmap bitmap){ if (bitmap == null) throw new ArgumentNullException("bitmap"); var rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height); var bitmapData = bitmap.LockBits( rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); try { var size = (rect.Width * rect.Height) * 4; return BitmapSource.Create( bitmap.Width, bitmap.Height, bitmap.HorizontalResolution, bitmap.VerticalResolution, PixelFormats.Bgra32, null, bitmapData.Scan0, size, bitmapData.Stride); } finally { bitmap.UnlockBits(bitmapData); }}
This solution requires the source image to be in Bgra32 format; if you are dealing with other formats, you may need to add a conversion.