我有一个不可搜索的流,其中包含一个 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); }
}