tags:

views:

3436

answers:

2

Hey guys,

How do I assing in memory Bitmap object to Image control in WPF??

PS: I googled about it but no luck :(

+6  A: 

According to http://khason.net/blog/how-to-use-systemdrawingbitmap-hbitmap-in-wpf/

   [DllImport("gdi32")]
   static extern int DeleteObject(IntPtr o);

   public static BitmapSource loadBitmap(System.Drawing.Bitmap source)
   {
       IntPtr ip = source.GetHbitmap();
       try
       {
           BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, 
              IntPtr.Zero, Int32Rect.Empty, 
              System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
       }
       finally
       {
           DeleteObject(ip);
       }

       return bs;
   }

It gets System.Drawing.Bitmap (from WindowsBased) and converts it into BitmapSource, which can be actually used as image source for your Image control in WPF.

image1.Source = YourUtilClass.loadBitmap(SomeBitmap);
Lars Truijens
Thx Lars, but I did much simpler, BitmapImage bmpi = new BitmapImage(); bmpi.BeginInit(); bmpi.StreamSource = new MemoryStream(ByteArray); bmpi.EndInit(); image1.Source = bmpi;
Prashant
Great. You can add your sollution as an answer to your own question.
Lars Truijens
I do not see a BitmapImage.StreamSource method. Prashant, did you type something wrong?
Patrick Szalapski
Or a property, for that matter.
Patrick Szalapski
Patrick, see http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.streamsource.aspx
Lars Truijens
+3  A: 

You can use the Source property of the image. Try this code...

ImageSource imageSource = new BitmapImage(new Uri("C:\\FileName.gif"));

image1.Source = imageSource;
Chalkey
He already has the bitmap in memory, so he can't use an uri
Lars Truijens
I have Bitmap object, actully it is generated from a scan device, so I cant refer to any location
Prashant
Oh okay sorry - see Lars Truijens' answer.
Chalkey