将.bmp作为.png保存到内存流时出现外部异常



我正在将一批.bmp转换为.png。这是代码的相关部分:

foreach (string path in files) {
using (fs = new FileStream(path, FileMode.Open)) bmp = new Bitmap(fs);
using (ms = new MemoryStream()) {
bmp.Save(ms, ImageFormat.Png);
bmp.Dispose();
png = Image.FromStream(ms);
}
png.Save(path);
}

在第bmp.Save(ms, ImageFormat.Png);行引发以下异常:

System.Runtime.InteropServices.ExternalException:"GDI+ 中发生一般错误。

根据MSDN的说法,这意味着图像要么以错误的格式保存,要么保存到读取图像的位置。后者不是这种情况。但是,我不明白我是如何给它错误的格式的:在同一个 MSDN 页面上给出了一个示例,其中.bmp以相同的方式转换为.gif。

这与我保存到内存流有关吗?这样做是为了我可以用转换后的文件覆盖原始文件。(请注意,.bmp后缀是有意保留的。这应该不是问题,因为在保存最终文件之前会出现异常。

在该位图构造函数的 MSDN 文档中,它说:

必须在位图的生存期内使流保持打开状态。

同样的评论可以在Image.FromStream上找到.

因此,您的代码应仔细处理它用于每个位图/图像的流的范围和生存期。

结合以下代码可以正确处理这些流:

foreach (string path in files) {
using (var ms = new MemoryStream()) //keep stream around
{
using (var fs = new FileStream(path, FileMode.Open)) // keep file around
{
// create and save bitmap to memorystream
using(var bmp = new Bitmap(fs))
{
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
}
}
// write the PNG back to the same file from the memorystream
using(var png = Image.FromStream(ms))
{
png.Save(path);
}
}
}

最新更新