C# GDI+;中发生一般性错误;(不是内存流)

C# GDI+;中发生一般性错误;(不是内存流),c#,image,gdi,C#,Image,Gdi,我得到以下例外情况: System.Runtime.InteropServices.ExternalException (0x80004005): A generic error occurred in GDI+. at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) at System.Drawing.Image.Save(St

我得到以下例外情况:

System.Runtime.InteropServices.ExternalException (0x80004005): A generic error occurred in GDI+.
    at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
    at System.Drawing.Image.Save(String filename, ImageFormat format)
代码如下:

public void foo()
{
    Image label = generateLabel(maxResolution.X, maxResolution.Y);
    label.Save(Path.Combine(Settings.LabelDirectory, currentDespatch.SalesOrderNumber + "-" + currentDespatch.DespatchNumber + ".png"), ImageFormat.Png);
}

 private Image generateLabel(int dpix, int dpiy)
{

    var ratio = 2;

    var margin = 50*ratio;

    // The printer defaults to 100 pixels per inch, hence 600x400 for a 6x4 label
    Bitmap img = new Bitmap(600*ratio, 400*ratio);

    img.SetResolution(dpix, dpiy);

    var canvas = Graphics.FromImage(img);

    Image barcode = Barcode.DoEncode(TYPE.CODE39, currentDespatch.SalesOrderNumber, true, 325*ratio, 140*ratio);            

    canvas.Clear(Color.White);
    canvas.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
    canvas.DrawImageUnscaledAndClipped(barcode, new Rectangle(img.Width - barcode.Width - (margin/4), margin, barcode.Width, barcode.Height));

    Font font = new Font("Arial", 17*ratio, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);
    Font small = new Font("Arial", 14*ratio, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
    Brush brush = new SolidBrush(Color.Black);

    canvas.DrawString("Hello world", font, brush, margin, img.Height - margin - (margin*2/3));
    canvas.DrawString("From label", small, brush, margin, img.Height - margin);
    canvas.Save();

    return img;
}
到目前为止,我找到的大多数答案都与我没有使用的内存流有关,因此我感到困惑

我认为这与GC在保存图像之前收集了一些对象有关,但我不清楚罪魁祸首在哪里

失败是间歇性的,因为它大部分时间都会成功,然后偶尔会失败,因此与权限无关


这是正在使用的条形码库:

如果您将我们的对象包装在一个using语句周围,以手动处理,这是我能想到的唯一一件事,查看您的代码类型39的条形码,允许使用一些特殊字符,包括正斜杠“/”。您的代码在输出文件名中使用相同的条形码字符串。如果其中一个文件名字符为“/”,Image.Save可能会引发类似的异常。否,订单号从来没有斜杠。这可能仍然是与文件名或某些其他权限问题相关的问题。要排除这种情况,请测试此代码,而不是当前使用的路径://首先保存一个虚拟小位图,以确保路径为OK bitmap bmp=new bitmap(4,4,PixelFormat.Format24bppRgb);bmp.SetPixel(2,2,颜色.绿黄色);保存(@“d:\test.png”,ImageFormat.png);Show(@“检查文件d:\test.png,然后单击OK”)//然后保存使用generateLabel()函数label生成的图像;