WPF - converting Bitmap to ImageSource

后端 未结 5 2210
天命终不由人
天命终不由人 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.

提交回复
热议问题