我正在创建一个包含任意值的字节数组,并希望将其转换为 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;
}
}
这段代码一直给我一个 NotSupportedException 。
如何从任何字节数组创建 BitmapSource?
最佳答案
给定一个字节数组,其中每个字节代表一个像素值,您可以创建如下所示的灰度位图。您需要指定位图的宽度和高度,当然必须与缓冲区大小匹配。
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);
每个字节值也可以代表调色板的索引,在这种情况下,您必须指定
PixelFormats.Indexed8
当然也可以传入一个合适的调色板。
关于wpf - 从字节数组创建 BitmapImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15274699/