How to create ImageBrush from System.Drawing.Image in WPF?

后端 未结 2 1204
忘掉有多难
忘掉有多难 2020-12-20 20:03

I have image in System.Drawing.Image object and I need to create an ImageBrush object (used for Fill property of Rectangle in WPF for example) from it. I guess there should

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-20 20:54

          var image = System.Drawing.Image.FromFile("..."); // or wherever it comes from
          var bitmap = new System.Drawing.Bitmap(image);
          var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(),
                                                                                IntPtr.Zero,
                                                                                Int32Rect.Empty,
                                                                                BitmapSizeOptions.FromEmptyOptions()
                );
          bitmap.Dispose();
          var brush = new ImageBrush(bitmapSource);          
    

    This solution, however, doesnt free the memory of the handle. For information on how to remove the memory leak see WPF CreateBitmapSourceFromHBitmap() memory leak

提交回复
热议问题