2

我有一个不可搜索的流,其中包含一个 PNG 文件。我想使用 WPF 的BitmapDecoder类对此进行解码。文档没有说明我必须传递一个可搜索的流,如果我这样做,代码也不会抛出,所以我认为它应该可以工作。

但是,我无法让它工作。这是一个显示问题的人为示例:

// This is an 8x8 all-red PNG:
var bytes = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLb"
            + "SncAAAAEElEQVQIHWP8z4AdMA4tCQB8/QgBp6L0HwAAAABJRU5ErkJggg==");

BitmapDecoder decoder;
using (var stream = new MemoryStream(bytes))
    decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.None,
                                   BitmapCacheOption.OnLoad);

Console.WriteLine(decoder.Frames[0].PixelWidth); // outputs 8, correctly

using (var stream = new UnseekableStream(new MemoryStream(bytes)))
    decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.None,
                                   BitmapCacheOption.OnLoad);

Console.WriteLine(decoder.Frames[0].PixelWidth); // outputs 1, wrongly

文档指出,如果我传入OnLoad标志,我应该能够立即处理流,我这样做了。

当然,我可以把整个事情读成MemoryStream第一个,但这听起来不对。我做错了什么,还是BitmapDecoder这里有问题?

PS 这是上面示例中使用的“压缩”源UnseekableStream

public sealed class UnseekableStream : Stream
{
    private Stream _stream;
    public UnseekableStream(Stream underlyingStream) { _stream = underlyingStream; }

    private bool _disposed = false;
    protected override void Dispose(bool disposing)
    {
        if (_disposed) return;
        _disposed = true; _stream.Dispose(); base.Dispose();
    }
    public override bool CanSeek { get { return false; } }
    public override bool CanWrite { get { return _stream.CanWrite; } }
    public override bool CanRead { get { return _stream.CanRead; } }
    public override void Flush() { _stream.Flush(); }
    public override long Length { get { return _stream.Length; } }
    public override void SetLength(long value) { _stream.SetLength(value); }
    public override long Position { get { return _stream.Position; } set { _stream.Position = value; } }
    public override long Seek(long offset, SeekOrigin origin) { return _stream.Seek(offset, origin); }
    public override int Read(byte[] buffer, int offset, int count) { return _stream.Read(buffer, offset, count); }
    public override void Write(byte[] buffer, int offset, int count) { _stream.Write(buffer, offset, count); }
}
4

1 回答 1

1

你可以PngBitmapDecoder直接使用:

using (var stream = new UnseekStream(new MemoryStream(bytes)))
{
    decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}

我猜这个流只需要在BitmapDecoder.Create合适的解码器实际解码之前就可以找到它包含的图像格式。

于 2013-01-11T21:55:56.623 回答