无法使用 JpegBitmapDecoder 解码 jpeg

xar*_*ria 2 wpf jpeg decoder

我有以下两个函数可以将字节转换为图像并在 WPF 中的图像上显示

 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;
        }
Run Code Online (Sandbox Code Playgroud)

上面的代码根本不起作用。我总是遇到“未找到成像组件”图像未显示的异常。

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;
    }
Run Code Online (Sandbox Code Playgroud)

此功能有效,但速度非常慢。我想优化我的代码。

Cle*_*ens 5

ConvertBytestoImageStream如果我传递给它一个 JPEG 缓冲区,你对我来说很好用。然而,有一些事情可以改进。根据您是否真的要返回解码器或位图,该方法可以这样编写:

private BitmapDecoder ConvertBytesToDecoder(byte[] buffer)
{
    using (MemoryStream stream = new MemoryStream(buffer))
    {
        return BitmapDecoder.Create(stream,
            BitmapCreateOptions.PreservePixelFormat,
            BitmapCacheOption.OnLoad); // enables closing the stream immediately
    }
}
Run Code Online (Sandbox Code Playgroud)

或者这样:

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];
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,此代码使用抽象基类BitmapDecoder的静态工厂方法,而不是使用 JpegBitmapDecoder ,它会自动为提供的数据流选择合适的解码器。因此,此代码可用于 WPF 支持的所有图像格式。

另请注意,Stream 对象在using 块使用,该负责在不再需要时处理它。BitmapCacheOption.OnLoad确保将整个流加载到解码器中,然后可以关闭。