How to convert from type Image to type BitmapImage?

Does anyone know how to create a BitmapImage from an image? Here is the code 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 it to the BitmapImage type in order to use it in my solution.

NOTE. I need to convert it to a BitmapImage type, not a Bitmap type. I could not figure it out because the BitmapImage type accepts a Uri constructor for it.

+6
source share
3 answers

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; } 
+3
source
 Bitmap img = (Bitmap) Image.FromStream(memStream); BitmapImage bmImg = new BitmapImage(); using (MemoryStream memStream2 = new MemoryStream()) { img.Save(memStream2, System.Drawing.Imaging.ImageFormat.Png); ms.Position = 0; bmImg.BeginInit(); bmImg.CacheOption = BitmapCacheOption.OnLoad; bmImg.UriSource = null; bmImg.StreamSource = memStream2; bmImg.EndInit(); } 
+6
source

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

For example, WriteableBitmap

http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap.aspx

You can make one of the required sizes, and then copy the pixels to it.

+1
source

Source: https://habr.com/ru/post/886651/


All Articles