尝试保存在本地编辑的图像时出现异常

Getting exception when trying to save an image that was edited locally

我正在尝试通过在图像上添加水印来编辑图像。我使用 Graphics 进行更改,当我尝试保存文件时它抛出异常 Message:"A generic error occurred in GDI+."

下面是我的代码:

    public static void Test()
    {
        try
        {
            Bitmap bmpPic = new Bitmap(Image.FromFile("Desktop/cropped/cropped/croppedsent1386.jpeg"));

            using (Graphics g = Graphics.FromImage(bmpPic))
            {
                Brush brush = new SolidBrush(Color.FromArgb(80, 255, 255, 255));
                Point postionWaterMark = new Point((bmpPic.Width / 6), (bmpPic.Height / 2));
                g.DrawString("Identifid", new System.Drawing.Font("Arial", 30, FontStyle.Bold, GraphicsUnit.Pixel), brush, postionWaterMark);

            }

            string filepath = "Desktop/cropped/cropped/croppedsent1386.jpeg";

            bmpPic.Save(filepath, ImageFormat.Jpeg);
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex);
        }

        Console.WriteLine("End of test ");
    }

-堆栈跟踪-

        StackTrace  "   at System.Drawing.SafeNativeMethods.Gdip.CheckStatus(Int32 status)\r\n   at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)\r\n   at System.Drawing.Image.Save(String filename, ImageFormat format)\r\n   at ConsoleWatermark.Program.Test() in C:\Users\xavie\source\repos\Samples\ConsoleWatermark\Program.cs:line 49" 

我很困惑为什么这会失败,因为我有编辑文件的权限。

出现错误是因为您试图覆盖(当 bmpPic.Save() 时)您已经加载为 Bitmap 的相同图像文件。直到 Bitmap 不会被处理 - 文件将被它锁定。要解决,你应该将新的水印图像保存到另一个新文件:

string filepath = ".../croppedsent1386_WATERMARKED.jpeg"; // <--- New file
bmpPic.Save(filepath, ImageFormat.Jpeg);

完整版(少许注解):

static void Main(string[] args)
{
    try
    {
        // Source image file
        string imageFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "myImage.png");

        // Add "using" to bitmap too for proper disposage and to release file after completion
        using (Bitmap bitmap = new Bitmap(Image.FromFile(imageFile)))
        {
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                Brush brush = new SolidBrush(Color.FromArgb(80, 255, 255, 255));
                Point watermarkPosition = new Point(bitmap.Width / 6, bitmap.Height / 2);

                g.DrawString("IDENTIFID", new Font("Arial", 30, FontStyle.Bold, GraphicsUnit.Pixel), brush, watermarkPosition);

                // Save to a new file
                string newImageFile = imageFile.Replace("myImage.png", "myImage_WATERMARKED.png");
                bitmap.Save(newImageFile, ImageFormat.Png);
            }
        }

        Console.WriteLine("Image saved!");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message + "\n\nStack trace:\n" + ex.StackTrace);
    }

    Console.ReadKey();
}