C#Image.Save以“无效的Bmp”结尾

时间:2013-11-20 13:17:50

标签: c# bitmap in-memory decoder

我尝试创建一个确实是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文件有效?

0 个答案:

没有答案