GDI +中发生了一般错误。在System.Drawing.Image.Save

时间:2014-07-31 04:10:32

标签: c# image bitmap

您好我在给定路径保存图片时收到此错误

string WriteImage(string data, string imgPath)
{           
    try
    {
        data = "*" + data + "*";
        Bitmap barcode = new Bitmap(1, 1);
        Font threeOfNine = new Font("IDAutomationHC39M", 60, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
        Graphics graphics = Graphics.FromImage(barcode);
        SizeF dataSize = graphics.MeasureString(data, threeOfNine);
        barcode = new Bitmap(barcode, dataSize.ToSize());
        graphics = Graphics.FromImage(barcode);
        graphics.Clear(Color.White);
        graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
        graphics.DrawString(data, threeOfNine, new SolidBrush(Color.Black), 0, 0);
        graphics.Flush();
        threeOfNine.Dispose();
        graphics.Dispose();
        barcode.SetResolution(300, 300);
        barcode.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
        return imgPath.Substring(imgPath.LastIndexOf("\\")+1);
    }
    catch
    {
        return "";
    }
}

不知道我做错了什么。

1 个答案:

答案 0 :(得分:2)

正如我在评论中所写,我没有看到任何问题。以下版本的代码在发生错误时输出信息,因此您可以对其进行调试。它还妥善处理资源:

    public static string WriteImage(string data, string imgPath)
    {
        try
        {
            data = "*" + data + "*";
            using (var dummyBitmap = new Bitmap(1, 1))
            using (var threeOfNine = new Font("IDAutomationHC39M", 60, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point))
            {
                SizeF dataSize;
                using (var graphics = Graphics.FromImage(dummyBitmap))
                {
                    dataSize = graphics.MeasureString(data, threeOfNine);
                }
                using (var barcode = new Bitmap(dummyBitmap, dataSize.ToSize()))
                using (var graphics = Graphics.FromImage(barcode))
                using (var brush = new SolidBrush(Color.Black))
                {
                    graphics.Clear(Color.White);
                    graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
                    graphics.DrawString(data, threeOfNine, brush, 0, 0);
                    graphics.Flush();
                    barcode.SetResolution(300, 300);
                    barcode.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    return imgPath.Substring(imgPath.LastIndexOf("\\") + 1);
                }
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Error saving string \"" + data + "\" to a bitmap at location: " + imgPath);
            Debug.WriteLine(ex.ToString());
            return "";
        }
    }