我从资源获取Image(实际上是Bitmap类的实例),并且(将其写入rtf流) - 我需要它的原始数据。
另外,Image.Save方法不能使用,因为它似乎关闭了它保存到的流,我需要附加到RTF文件。我不想创建新的流,将图像保存到它,然后由于性能问题将其复制到RTF流。
答案 0 :(得分:3)
创建一个过滤器流,该过滤器流将传递给您要附加到的流,但在它自身关闭时不会关闭该流:
public class AppendingStream : Stream
{
private readonly long _startPos;
private readonly Stream _sink;
public AppendingStream(Stream sink)
{
if(sink == null)
throw new ArgumentNullException();
if(!sink.CanWrite)
throw new ArgumentException();
_sink = sink;
try
{
_startPos = sink.Position;
}
catch(NotSupportedException)
{
_startPos = -1;
}
}
public override bool CanRead
{
get
{
return false;
}
}
public override bool CanSeek
{
get
{
return _sink.CanSeek && _startPos != -1;
}
}
public override bool CanTimeout
{
get
{
return _sink.CanTimeout;
}
}
public override bool CanWrite
{
get
{
return true;
}
}
public override long Length
{
get
{
if(_startPos == -1)
throw new NotSupportedException();
return _sink.Length - _startPos;
}
}
public override long Position
{
get
{
return _sink.Position - _startPos;
}
set
{
_sink.Position = value + _startPos;
}
}
public override void Flush()
{
_sink.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override int ReadByte()
{
throw new NotSupportedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
if(origin == SeekOrigin.Begin)
return _sink.Seek(offset + _startPos, SeekOrigin.Begin) - _startPos;
else
return _sink.Seek(offset, origin);
}
public override void SetLength(long value)
{
if(_startPos == -1)
throw new NotSupportedException();
_sink.SetLength(value + _startPos);
}
public override void Write(byte[] buffer, int offset, int count)
{
_sink.Write(buffer, offset, count);
}
public override void WriteByte(byte value)
{
_sink.WriteByte(value);
}
}
然后你就不再有关闭流的问题,因为它没关系。
处理寻找新位置的位是因为某些图像格式是以非顺序方式写入的。如果底层流不支持它,它将无法工作,但那无论如何都无法工作。