ger*_*tla 12 wpf image type-conversion bitmapimage
我有一个byte[]
代表图像的原始数据.我想把它转换为BitmapImage
.
我尝试了几个我发现的例子但是我一直得到以下异常
"没有找到适合完成此操作的成像组件."
我认为这是因为我byte[]
实际上并不代表图像而只是原始位.所以我的问题如上所述是如何将原始位的byte []转换为a BitmapImage
.
Eir*_*rik 12
public static BitmapImage LoadFromBytes(byte[] bytes)
{
using (var stream = new MemoryStream(bytes))
{
stream.Seek(0, SeekOrigin.Begin);
var image = new BitmapImage();
image.BeginInit();
image.StreamSource = stream;
image.EndInit();
return image;
}
}
Run Code Online (Sandbox Code Playgroud)
当您的字节数组包含位图的原始像素数据时,您可以通过静态方法创建BitmapSource
(它是基类BitmapImage
)BitmapSource.Create
.
但是,您需要指定位图的一些参数.您必须事先知道宽度和高度以及PixelFormat
缓冲区的宽度和高度.
byte[] buffer = ...;
var width = 100; // for example
var height = 100; // for example
var dpiX = 96d;
var dpiY = 96d;
var pixelFormat = PixelFormats.Pbgra32; // for example
var bytesPerPixel = (pixelFormat.BitsPerPixel + 7) / 8;
var stride = bytesPerPixel * width;
var bitmap = BitmapSource.Create(width, height, dpiX, dpiY,
pixelFormat, null, buffer, stride);
Run Code Online (Sandbox Code Playgroud)