質問

ストリームについて多くのことを知りません。最初のバージョンがファイルを使用して機能するのはなぜですか? 「Return Dest;」にブレークポイントを置く;どちらもまったく同じものを作成したように見えますが、Destは常に2番目のバージョンを使用して空白の画像です。

    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;
}
役に立ちましたか?

解決

指定する必要があります 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;
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top