- Freezeを行わないと、別スレッドから触った際にエラーとなる
- DeleteObjectを行わないとメモリリークが発生する
public static class BitmapToImageSource
{
[DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeleteObject([In] IntPtr hObject);
/// <summary>
/// BitmapからImageSourceへコンバート
/// </summary>
/// <param name="_Bitmap"></param>
/// <returns></returns>
public static ImageSource Convert(Bitmap _Bitmap)
{
ImageSource objResult = null;
if (_Bitmap != null)
{
var objHandle = _Bitmap.GetHbitmap();
try
{
objResult = Imaging.CreateBitmapSourceFromHBitmap(objHandle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
objResult.Freeze();
}
finally
{
DeleteObject(objHandle);
}
}
return objResult;
}
}