wpf 从字节数组创建 BitmapImage
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15274699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a BitmapImage from a byte array
提问by tabina
I am creating a byte array with arbitrary values in it and want to convert it into a BitmapImage.
我正在创建一个包含任意值的字节数组,并希望将其转换为 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 all the time. How could I create a BitmapSource from any byte array?
这段代码一直给我一个 NotSupportedException 。如何从任何字节数组创建 BitmapSource?
回答by Clemens
Given an array of bytes where each byte represents a pixel value, you may create a grayscale bitmap like shown below. You need to specify the width and height of the bitmap, and that must of course match the buffer size.
给定一个字节数组,其中每个字节代表一个像素值,您可以创建如下所示的灰度位图。您需要指定位图的宽度和高度,当然这必须与缓冲区大小匹配。
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 may also represent an index into a color palette, in which case your would have to specify PixelFormats.Indexed8and of course also pass in an appropriate color palette.
每个字节值也可能代表一个调色板的索引,在这种情况下,您必须指定PixelFormats.Indexed8并且当然也传递适当的调色板。
回答by doerig
The byte array must contain valid image data (PNG / JPG / BMP).
If you remove the using-block and the data is valid then your Code should work. BitmapImage doesn't seem to load the image immediatly, so it can't load it afterwards because the stream is already disposed.
字节数组必须包含有效的图像数据(PNG / JPG / BMP)。
如果您删除 using-block 并且数据有效,那么您的代码应该可以工作。BitmapImage 似乎不会立即加载图像,因此它之后无法加载它,因为流已经被释放。
What do you mean by "arbitrary values"? Random RGB values? Then I propose to use the Bitmapclass and save the resulting Bitmap in a Memorystream.
“任意值”是什么意思?随机 RGB 值?然后我建议使用Bitmap类并将生成的 Bitmap 保存在 Memorystream 中。
If you just want to bind a Byte[] to and Image Control in your userinterface: Bind directly to the array. It works without a converter.
如果您只想将 Byte[] 绑定到用户界面中的 Image Control:直接绑定到数组。它无需转换器即可工作。

