本文介绍了如何将byte []转换为BitmapImage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 byte [] ,它代表图像的原始数据。我想将它转换为 BitmapImage

I have a byte[] that represents the raw data of an image. I would like to convert it to a BitmapImage.

我尝试了几个我发现的例子,但我一直得到以下异常

I tried several examples I found but I kept getting the following exception

我认为这是因为我的 byte [] 实际上并不代表一个Image而只代表原始位。
所以我的问题如上所述是如何将原始位的byte []转换为 BitmapImage

I think it is because my byte[] does not actually represent an Image but only the raw bits.so my question is as mentioned above is how to convert a byte[] of raw bits to a BitmapImage.

推荐答案

当您的字节数组包含位图的原始像素数据时,您可以创建 BitmapSource (这是基类 BitmapImage )通过静态方法。

When your byte array contains a bitmap's raw pixel data, you may create a BitmapSource (which is the base class of BitmapImage) by the static method BitmapSource.Create.

但是,您需要指定位图的一些参数。您必须事先知道宽度和高度以及缓冲区。

However, you need to specify a few parameters of the bitmap. You must know in advance the width and height and also the PixelFormat of the buffer.

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);

这篇关于如何将byte []转换为BitmapImage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 22:15