Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - WPF - converting Bitmap to ImageSource

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

The converter was found by me here. I get a NullReferenceException at

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...