Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 329
user3489135 Avatar asked Oct 08 '14 15:10

user3489135


2 Answers

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); }               
    }
like image 174
dethSwatch Avatar answered Oct 18 '22 03:10

dethSwatch


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;
        }
    }
}
like image 31
JsAndDotNet Avatar answered Oct 18 '22 01:10

JsAndDotNet