WPF - converting Bitmap to ImageSource

后端 未结 5 2195
天命终不由人
天命终不由人 2020-12-05 02:50

I need to convert a System.Drawing.Bitmap into System.Windows.Media.ImageSource class in order to bind it into a HeaderImage control of a WizardPag

相关标签:
5条回答
  • 2020-12-05 03:12

    I do not believe that ImageSourceConverter will convert from a System.Drawing.Bitmap. However, you can use the following:

    public static BitmapSource CreateBitmapSourceFromGdiBitmap(Bitmap bitmap)
    {
        if (bitmap == null)
            throw new ArgumentNullException("bitmap");
    
        var rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
    
        var bitmapData = bitmap.LockBits(
            rect,
            ImageLockMode.ReadWrite,
            PixelFormat.Format32bppArgb);
    
        try
        {
            var size = (rect.Width * rect.Height) * 4;
    
            return BitmapSource.Create(
                bitmap.Width,
                bitmap.Height,
                bitmap.HorizontalResolution,
                bitmap.VerticalResolution,
                PixelFormats.Bgra32,
                null,
                bitmapData.Scan0,
                size,
                bitmapData.Stride);
        }
        finally
        {
            bitmap.UnlockBits(bitmapData);
        }
    }
    

    This solution requires the source image to be in Bgra32 format; if you are dealing with other formats, you may need to add a conversion.

    0 讨论(0)
  • 2020-12-05 03:16

    For others, this works:

        //If you get 'dllimport unknown'-, then add 'using System.Runtime.InteropServices;'
        [DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool DeleteObject([In] IntPtr hObject);
    
        public ImageSource ImageSourceFromBitmap(Bitmap bmp)
        {
            var handle = bmp.GetHbitmap();
            try
            {
                return Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            }
            finally { DeleteObject(handle); }               
        }
    
    0 讨论(0)
  • 2020-12-05 03:16

    For the benefit of searchers, I created a quick converter based on a this more detailed solution.

    No problems so far.

    using System;
    using System.Drawing;
    using System.IO;
    using System.Windows.Media.Imaging;
    
    namespace XYZ.Helpers
    {
        public class ConvertBitmapToBitmapImage
        {
            /// <summary>
            /// Takes a bitmap and converts it to an image that can be handled by WPF ImageBrush
            /// </summary>
            /// <param name="src">A bitmap image</param>
            /// <returns>The image as a BitmapImage for WPF</returns>
            public BitmapImage Convert(Bitmap src)
            {
                MemoryStream ms = new MemoryStream();
                ((System.Drawing.Bitmap)src).Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                BitmapImage image = new BitmapImage();
                image.BeginInit();
                ms.Seek(0, SeekOrigin.Begin);
                image.StreamSource = ms;
                image.EndInit();
                return image;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-05 03:18

    dethSwatch - Thank you for your answer above! It helped tremendously! After implementing it I was getting the desired behavior but I found I was getting a memory/handle issue in another section of my program. I changed the code as follows, making it a little more verbose and the issue went away. Thank you again!

        [DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool DeleteObject([In] IntPtr hObject);
    
        public ImageSource ImageSourceForBitmap(Bitmap bmp)
        {
            var handle = bmp.GetHbitmap();
            try
            {
                ImageSource newSource = Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
    
                DeleteObject(handle);
                return newSource;
            }
            catch (Exception ex)
            {
                DeleteObject(handle);
                return null;
            }
        }
    
    0 讨论(0)
  • 2020-12-05 03:28

    The simpliest solution for me:

    ImageBrush myBrush = new ImageBrush();
    var bitmap = System.Drawing.Image.FromFile("pic1.bmp");
    Bitmap bitmap = new System.Drawing.Bitmap(image);//it is in the memory now
    var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(),IntPtr.Zero,Int32Rect.Empty,BitmapSizeOptions.FromEmptyOptions());
    myBrush.ImageSource = bitmapSource;
    cover.MainGrid.Background = myBrush;
    cover.Show();
    bitmap.Dispose();
    
    0 讨论(0)
提交回复
热议问题