A
A
Avery0072014-10-17 15:06:51
WPF
Avery007, 2014-10-17 15:06:51

How to display System.Drawing.Bitmap in Image?

I know that there are converters from Bitmap to BitmapImage, but I have a System.Drawing.Graphics(Graphics.FromImage) object initialized for this Bitmap. It is very resource-intensive to perform the conversion every time the Bitmap is changed via Graphics. How to be?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Buraikin, 2014-10-21
@bstdman

Resource-intensive - perhaps if you do not clear the memory after the conversion using WinApi.
img - Bitmap

var img = new Bitmap(pictureSize.Width, pictureSize.Height);
            Graphics g = Graphics.FromImage(img);

            //
            // Здесь ваше рисование с использованием объекта g
            //

            g.Dispose();
            IntPtr hBitmap = img.GetHbitmap();
            BitmapSource src;
            try
            {
                src = Imaging.CreateBitmapSourceFromHBitmap(hBitmap,
                                                            IntPtr.Zero,
                                                            Int32Rect.Empty,
                                                            BitmapSizeOptions.
                                                                FromEmptyOptions());
                src.Freeze();
            }
            finally
            {
                DeleteObject(hBitmap);
            }

            return src;

[DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question