Creating BitmapImage from Byte Array

I am creating an array of bytes with arbitrary values ​​in it and want to convert it to BitmapImage.

bi = new BitmapImage(); using (MemoryStream stream = new MemoryStream(data)) { try { bi.BeginInit(); bi.CacheOption = BitmapCacheOption.OnLoad; bi.StreamSource = stream; bi.DecodePixelWidth = width; bi.EndInit(); } catch (Exception ex) { return null; } } 

This code gives me a NotSupportedException. How can I create a BitmapSource from any byte array?

+3
source share
2 answers

Given an array of bytes, where each byte represents a pixel value, you can create a bitmap in grayscale, as shown below. You need to specify the width and height of the bitmap, and this, of course, should match the size of the buffer.

 byte[] buffer = ... // must be at least 10000 bytes long in this example var width = 100; // for example var height = 100; // for example var dpiX = 96d; var dpiY = 96d; var pixelFormat = PixelFormats.Gray8; // grayscale bitmap var bytesPerPixel = (pixelFormat.BitsPerPixel + 7) / 8; // == 1 in this example var stride = bytesPerPixel * width; // == width in this example var bitmap = BitmapSource.Create(width, height, dpiX, dpiY, pixelFormat, null, buffer, stride); 

Each byte value can also be an index in the color palette, in which case you will need to specify PixelFormats.Indexed8 and, of course, pass the corresponding color palette.

+7
source

The byte array must contain valid image data (PNG / JPG / BMP). If you delete the used block and the data is valid, your code should work. BitmapImage does not seem to load the image right away, so it cannot load it after the stream has already been deleted.

What do you mean by "arbitrary values"? Random RGB values? Then I suggest using the Bitmap class and save the resulting Bitmap to Memorystream.

If you just want to bind Byte [] and Image Control in your user interface: bind directly to an array. It works without a converter.

+1
source

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


All Articles