How to get BitmapSource from System.Drawing.Bitmap in C# 3.5

public BitmapSource getBitmapSourceFromBitmap(Bitmap bmp)

{

BitmapSource returnSource = null;

try

{

returnSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(),

IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

}

catch { returnSource = null; }

return returnSource;

}



...S.VinothkumaR.

3 comments:

  1. I thought you would like to know that this process produces a memory leak as the GC cannot collect the Hbitmap.

    To remedy this you must import the gid32.dll to delete the object.
    [System.Runtime.InteropServices.DllImport("gdi32.dll")]
    public static extern bool DeleteObject(IntPtr hObject);

    However there must be a better solution.

    ReplyDelete