System.Drawing.Imageのインスタンスがあります。
これをWPFアプリケーションで表示するにはどうすればよいですか?
試してみましimg.Source
たが、うまくいきません。
私は同じ問題を抱えており、いくつかの回答を組み合わせて解決します。
System.Drawing.Bitmap bmp;
Image image;
...
using (var ms = new MemoryStream())
{
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Position = 0;
var bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.StreamSource = ms;
bi.EndInit();
}
image.Source = bi;
//bmp.Dispose(); //if bmp is not used further. Thanks @Peter
この質問と回答から
Image を WPF Image コントロールにロードするには、System.Windows.Media.ImageSource が必要です。
Drawing.Image オブジェクトを ImageSource オブジェクトに変換する必要があります。
public static BitmapSource GetImageStream(Image myImage)
{
var bitmap = new Bitmap(myImage);
IntPtr bmpPt = bitmap.GetHbitmap();
BitmapSource bitmapSource =
System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
bmpPt,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
//freeze bitmapSource and clear memory to avoid memory leaks
bitmapSource.Freeze();
DeleteObject(bmpPt);
return bitmapSource;
}
DeleteObject メソッドの宣言。
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteObject(IntPtr value);