C# 将.bmp另存为.png时发生外部异常

C# 将.bmp另存为.png时发生外部异常,c#,image,stream,C#,Image,Stream,我正在将一批.bmp转换为.png。这是守则的相关部分: foreach(文件中的字符串路径){ 使用(fs=newfilestream(path,FileMode.Open))bmp=newbitmap(fs); 使用(ms=newmemoryStream()){ 保存(ms,ImageFormat.Png); bmp.Dispose(); png=Image.FromStream(毫秒); } 保存(路径); } 在行bmp.Save(ms,ImageFormat.Png)引发以下异常:

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

foreach(文件中的字符串路径){
使用(fs=newfilestream(path,FileMode.Open))bmp=newbitmap(fs);
使用(ms=newmemoryStream()){
保存(ms,ImageFormat.Png);
bmp.Dispose();
png=Image.FromStream(毫秒);
}
保存(路径);
}
在行
bmp.Save(ms,ImageFormat.Png)引发以下异常:

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

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


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

的MSDN文档中指出:

您必须在位图的生存期内保持流打开

同样的话也可以在网上找到

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

结合以下代码正确处理这些流的所有功能:

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);
        }
    }
}

尝试保持第一个使用块处于活动状态。可能是第一个位图的基础流正在关闭。您需要使用ImageFromFile。见: