25

System.Drawing.Imageのインスタンスがあります。

これをWPFアプリケーションで表示するにはどうすればよいですか?

試してみましimg.Sourceたが、うまくいきません。

4

3 に答える 3

26

私は同じ問題を抱えており、いくつかの回答を組み合わせて解決します。

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

この質問と回答から

于 2012-04-26T14:20:25.133 に答える
20

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);
于 2012-04-09T18:22:50.217 に答える