我有以下两个函数将字节转换为图像并在WPF中的Image上显示
private JpegBitmapDecoder ConvertBytestoImageStream(byte[] imageData)
{
Stream imageStreamSource = new MemoryStream(imageData);
JpegBitmapDecoder decoder = new JpegBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];
return decoder;
}
以上代码根本不起作用。我总是得到“未找到成像组件”的例外情况。图像未显示。
private MemoryStream ConvertBytestoImageStream(int CameraId, byte[] ImageData, int imgWidth, int imgHeight, DateTime detectTime)
{
GCHandle gch = GCHandle.Alloc(ImageData, GCHandleType.Pinned);
int stride = 4 * ((24 * imgWidth + 31) / 32);
Bitmap bmp = new Bitmap(imgWidth, imgHeight, stride, PixelFormat.Format24bppRgb, gch.AddrOfPinnedObject());
MemoryStream ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Jpeg);
gch.Free();
return ms;
}
此功能有效,但速度很慢。我希望优化我的代码。
答案 0 :(得分:4)
如果我将JPEG缓冲区传递给你,ConvertBytestoImageStream
对我来说很好。然而,有一些事情可以改进。根据您是否真的想要返回解码器或位图,可以用这种方式编写方法:
private BitmapDecoder ConvertBytesToDecoder(byte[] buffer)
{
using (MemoryStream stream = new MemoryStream(buffer))
{
return BitmapDecoder.Create(stream,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.OnLoad); // enables closing the stream immediately
}
}
或者这样:
private ImageSource ConvertBytesToImage(byte[] buffer)
{
using (MemoryStream stream = new MemoryStream(buffer))
{
BitmapDecoder decoder = BitmapDecoder.Create(stream,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.OnLoad); // enables closing the stream immediately
return decoder.Frames[0];
}
}
请注意,此代码不使用JpegBitmapDecoder,而是使用抽象基类BitmapDecoder的静态工厂方法,该方法会自动为提供的数据流选择合适的解码器。因此,此代码可用于WPF支持的所有图像格式。
另请注意,Stream对象在using block内部使用,它在不再需要时处理它。 BitmapCacheOption.OnLoad确保将整个流加载到解码器中,然后可以关闭。