tab*_*ina 5 wpf bitmapimage notsupportedexception
我正在创建一个包含任意值的字节数组,并希望将其转换为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;
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码一直给我一个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);
Run Code Online (Sandbox Code Playgroud)
每个字节值也可以表示调色板的索引,在这种情况下,您必须指定PixelFormats.Indexed8并且当然也传递适当的调色板.