转换位图的ImageSource

转换位图的ImageSource

本文介绍了WPF - 转换位图的ImageSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个System.Drawing.Bitmap转换成System.Windows.Media.ImageSource类,以将其绑定到一个WizardPage(扩展WPF工具)的标题图片控制。
该位被设置为我写的组件的资源。
它被引用这样的:

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 WizardPage (Extended WPF toolkit).The bitmap is set as a resource of the assembly I write.It is being referenced like that:

     public Bitmap GetBitmap
     {
         get
         {
             Bitmap bitmap = new Bitmap(Resources.my_banner);
             return bitmap;
         }
     }

     public ImageSource HeaderBitmap
     {
         get
         {
             ImageSourceConverter c = new ImageSourceConverter();
             return (ImageSource) c.ConvertFrom(GetBitmap);
         }
     }

该转换器是由我在这里找到:的
我得到一个NullReferenceException

The converter was found by me here: http://www.codeproject.com/Questions/621920/How-to-convert-Bitmap-to-ImageSourceI get a NullReferenceException at

收益率(ImageSource的)c.ConvertFrom(Resources.my_banner);
我怎么能初始化的ImageSource为了避免这种例外?或有另一种方式?
我想以后要使用它,如:

return (ImageSource) c.ConvertFrom(Resources.my_banner);How can i initialize ImageSource in order to avoid this exception? Or is there another way?I want to use it afterwards like:

        <xctk:WizardPage x:Name="StartPage" Height="500" Width="700"
                     HeaderImage="{Binding HeaderBitmap}" Enter="StartPage_OnEnter"

感谢您预先的任何答案。

Thanks in advance for any answers.

推荐答案

我不相信 ImageSourceConverter 将从 System.Drawing中进行转换。位图。但是,您可以使用以下命令:

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);
    }
}

这个解决方案需要与源图像是在Bgra32格式;如果你正在处理其它格式,你可能需要增加一个转换。

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.

这篇关于WPF - 转换位图的ImageSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:19