【问题标题】:PngBitmapDecoder stream questionPngBitmapDecoder 流问题
【发布时间】:2011-09-15 21:51:20
【问题描述】:

不太了解流。为什么第一个版本可以使用文件,而第二个版本不行?在“return dest;”上设置断点;看起来两者都创建了完全相同的东西,但 dest 使用第二个版本始终是空白图像。

    public static BitmapSource ConvertByteArrayToBitmapSource(Byte[] imageBytes, ImageFormat formatOfImage)
{
    BitmapSource dest = null;
    if (formatOfImage == ImageFormat.Png)
    {
        var streamOut = new FileStream("tmp.png", FileMode.Create);
        streamOut.Write(imageBytes, 0, imageBytes.Length);
        streamOut.Close();

        Uri myUri = new Uri("tmp.png", UriKind.RelativeOrAbsolute);
        var bdecoder2 = new PngBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
        dest = bdecoder2.Frames[0];
    }

    return dest;
}

public static BitmapSource ConvertByteArrayToBitmapSource_NoWork(Byte[] imageBytes, ImageFormat formatOfImage)
{
    BitmapSource dest = null;
    using (var stream = new MemoryStream(imageBytes))
    {
        var bdecoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
        stream.Flush();
        dest = bdecoder.Frames[0];
        stream.Close();
    }

    return dest;
}

【问题讨论】:

  • 为什么叫 Flush ?没有它还能用吗?
  • 如果可以直接从流中创建BitmapImage,为什么还要使用特定的解码器?
  • 冲洗或不冲洗不起作用。我需要一个 BitmapSource 而不是 BitmapImage。基本上我将值从 BitmapSource 保存到 db 作为 array[] 然后将其恢复为 BitmapSource。

标签: c# wpf stream bitmapsource


【解决方案1】:

您必须指定BitmapCacheOption.OnLoad,否则位图将在第一次显示时被加载。然而,流已经被释放了。

另外,看看这个版本支持不同的图像格式并冻结图像以获得更好的性能:

public static BitmapSource ConvertByteArrayToBitmapSource(Byte[] imageBytes)
{
    using (MemoryStream stream = new MemoryStream(imageBytes))
    {
        BitmapDecoder deconder = BitmapDecoder.Create(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
        BitmapFrame frame = deconder.Frames.First();

        frame.Freeze();
        return frame;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    相关资源
    最近更新 更多