How to convert from type Image to type BitmapImage?

Does anyone know how to create a BitmapImage from an Image? Here is the code that I'm working with:

MemoryStream memStream = new MemoryStream(bytes); Image img = Image.FromStream(memStream); 

Now I have access to this image in memory. The thing is I need to convert this to type BitmapImage in order to use it in my solution.

NOTE: I need to convert it to type BitmapImage not type Bitmap. I haven't been able to figure it out because type BitmapImage takes in a Uri for it's constructor.

4 Answers

Bitmap img = (Bitmap) Image.FromStream(memStream); BitmapImage bmImg = new BitmapImage(); using (MemoryStream memStream2 = new MemoryStream()) { img.Save(memStream2, System.Drawing.Imaging.ImageFormat.Png); memStream2.Position = 0; bmImg.BeginInit(); bmImg.CacheOption = BitmapCacheOption.OnLoad; bmImg.UriSource = null; bmImg.StreamSource = memStream2; bmImg.EndInit(); } 
3

From this post

public BitmapImage ImageFromBuffer(Byte[] bytes) { MemoryStream stream = new MemoryStream(bytes); BitmapImage image = new BitmapImage(); image.BeginInit(); image.StreamSource = stream; image.EndInit(); return image; } 
2

Are you sure you need BitmapImage, not BitmapSource? BitmapImage is a subclass of BitmapSource specifically for making a source in XAML (from a URI). There are many other BitmapSource choices -- one of the other choices might be better.

For example, WriteableBitmap

You can make one of the size you want, and then copy pixels over to it.

Saving in a memory stream doesn't work for images created in memory. So I improved the already existing answers as follows:

ImageConverter converter = new ImageConverter(); byte[] buffer = (byte[])converter.ConvertTo(image, typeof(byte[])); MemoryStream loadStream = new MemoryStream(buffer); BitmapImage returnValue = new(); returnValue.BeginInit(); returnValue.StreamSource = loadStream; returnValue.EndInit(); return returnValue; 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like