The is a way to convert to convert
System.Drawing.Bitmap
into
System.Windows.Media.Imaging.BitmapSource
.
Do the following:
using System;
using System.Windows;
using BitmapSource = System.Windows.Media.Imaging.BitmapSource;
using InteropImaging = System.Windows.Interop.Imaging;
using System.Drawing.Imaging;
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr hObject);
public static BitmapSource CreateBitmapSourceFromBitmap(System.Drawing.Bitmap bitmap) {
IntPtr hBitmap = bitmap.GetHbitmap();
try {
return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
} finally {
DeleteObject(hBitmap);
}
}
Another way it to create a memory stream, write a bitmap to it and then read from it. You convert by writing using one system and reading by another one. As
System.Windows.Interop.Imaging
already does the trick you may not need it.
(In principle, you can ignore the problem with deletion of the intermediate bitmap and the resource leak to avoid using P/Invoke. If you do it just fixed number of times (say, once or twice) you can ignore the leak. Be careful.)
—SA