我尝试创建一个确实是System.Drawing.Bitmap的对象的内存流。 MemoryStream
稍后作为临时文件保存在磁盘上。
这是代码:
object resource = TestData.ResourceManager.GetObject(key);
...
if (resource is System.Drawing.Bitmap)
{
MemoryStream memoryStream = new MemoryStream();
Encoder myEncoder = System.Drawing.Imaging.Encoder.ColorDepth;
EncoderParameters myEncoderParameters = new EncoderParameters();
myEncoderParameters.Param[0] = new EncoderParameter(myEncoder, 16);
((System.Drawing.Bitmap)resource).Save(memoryStream, ImageFormat.Bmp);
return memoryStream;
}
...
然后保存内存流:
string targetFilePath = Path.GetTempFileName();
using (MemoryStream resourceStream = ResolveAsStream(key))
{
if (resourceStream == null)
{
throw new InvalidOperationException("Could not find resource for key '" + key + "'.");
}
using (FileStream fs = new FileStream(targetFilePath, FileMode.Open, FileAccess.Write))
{
resourceStream.CopyTo(fs);
}
}
return targetFilePath;
文件已成功创建,但当我尝试打开它时,它告诉我,图像文件无效(即,无法通过Paint或任何其他图像查看器打开它)。我尝试使用ImageFormat.Bmp
:
ImageFormat.MemoryBmp
object resource = TestData.ResourceManager.GetObject(key);
...
if (resource is System.Drawing.Bitmap)
{
MemoryStream memoryStream = new MemoryStream();
Encoder myEncoder = System.Drawing.Imaging.Encoder.ColorDepth;
EncoderParameters myEncoderParameters = new EncoderParameters();
myEncoderParameters.Param[0] = new EncoderParameter(myEncoder, 16);
((System.Drawing.Bitmap)resource).Save(memoryStream, ImageFormat.MemoryBmp);
return memoryStream;
}
...
但这实际上失败了
“value不能为null参数名称:encoder”
似乎没有为MemoryBmp
指定编解码器。那么如何正确保存图像以使Bmp
文件有效?