繁体   English   中英

GDI+ 中的 System.Drawing.Image.Save 发生一般性错误

[英]A generic error occurred in GDI+ at System.Drawing.Image.Save

例外:

GDI+ 中发生一般性错误。 在 System.Drawing.Image.Save(字符串文件名,ImageCodecInfo 编码器,EncoderParameters encoderParams)在 System.Drawing.Image.Save(字符串文件名,ImageFormat 格式)在 System.Drawing.Image.Save(字符串文件名)

代码:

byte[] bitmapData = new byte[imageText.Length];
MemoryStream streamBitmap;
bitmapData = Convert.FromBase64String(imageText);
streamBitmap = new MemoryStream(bitmapData);
System.Drawing.Image img = Image.FromStream(streamBitmap);
img.Save(path);

我们将一个 base64 字符串转换为 MemoryStream,然后创建一个 System.Drawing.Image (Image.FromStream(streamBitmap))。 最后图像被保存在一个临时文件中。

奇怪的是,问题似乎是在web服务器上的活动(并发用户数)很高时出现的,并且在IISRESET或应用程序池回收后问题暂时解决了......

==> 垃圾收集器问题?

我已经检查了 TEMP 文件夹的权限...

当您从流加载图像时,您必须在图像的生命周期内保持流打开,请参阅此MSDN Image.FromStream

我认为这个异常是因为内存流在图像被处理之前就被关闭了。 您可以像这样更改代码:

byte[] bitmapData = new byte[imageText.Length];
bitmapData = Convert.FromBase64String(imageText);

  using (var streamBitmap = new MemoryStream(bitmapData))
  {
      using (img = Image.FromStream(streamBitmap))
      { 
         img.Save(path);
      }
  }

以下是一些讨论类似问题的线程的链接:

gdi+ 从网页保存图像时出错

绘制图像时:System.Runtime.InteropServices.ExternalException:GDI 中发生一般错误

确保您指定的路径有效。 如果文件路径不存在,使用之前的答案(使用内存流),您可能仍然会收到此确切错误“GDI+ 中的通用错误”。 将创建文件,目录路径必须存在。

我在保存图像时遇到了相同的异常消息。 结果证明我的代码很好,并且做了它应该做的事情。

问题是硬盘已满,因此无法创建新映像。 我只是在尝试保存我正在处理的项目时注意到这一点,因为它没有空间可以保存。

在我的情况下,下面的代码片段工作正常,其中ConvertedImageString是从 API 接收的 Base64Image 字符串,我将其转换为具有某种格式的相关图像,并将其保存到服务器上的物理文件夹中。

编辑:发生上述错误可能是因为您尝试保存图像的文件路径错误

string converted = ConvertedImageString.Replace('-', '+');
converted = converted.Replace('_', '/');
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(ConvertedImageString)))
{
    using (Bitmap bm1 = new Bitmap(ms))
    {
        newFileName =  id + ".jpg";
        newFileName = CleanFileName(newFileName);
        newFileName = newFileName.Replace(" ", "_");

        Path = Path + newFileName;

        bm1.Save(Path, ImageFormat.Jpeg);
    }
}

当您调用“Image.FromFile”或“Image.Save”时,图像对象将锁定文件,直到它被明确释放。 如果您对相同的文件名执行另一个“Image.Save”或“Image.FromFile”,您可能会收到“通用错误”异常。 这取决于垃圾收集器是否已经处理了图像,因此结果不一致。

如果在“保存”操作后不需要该图像,则应立即处理它。 如果您确实需要该图像,Image.Clone 将制作一个不锁定源文件的副本。

我在 Image Library Editing 应用程序中遇到过这个问题,这是一个解决方案。

我收到此错误是因为我尝试将图像保存到的文件夹不存在 并且image.Save(string path)不会自动创建文件夹。 所以这是你必须以编程方式创建文件夹的东西

if (Directory.Exists(folderToUpload) == false)
{
    Directory.CreateDirectory(folderToUpload);
}

然后您应该能够将图像保存到所需位置。

此错误是由于图像已在使用中。 无论您在何处使用图像,都将图像转换为字符串 base 64 格式并使用它。 这将解决错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM