将日期和时间添加到保存的图片时,GDI+ 中出现一般错误

A generic error occured in GDI+ while adding date and time into the saved picture

我想创建一个简单的捕获活动 window。所以,我像下面的代码一样创建它:

string _dateTime = DateTime.Now.ToString("dd/MM/yyyy");

        Rectangle bounds = this.Bounds;

        try
        {
            using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
            {
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
                }

                bitmap.Save("D:/Test/Screenshot - " + _dateTime + " -.jpg", ImageFormat.Jpeg);

                SystemManager.ShowMessageBox("Success!", "Success", 1);
            }
        }

        catch (Exception ex)
        {
            SystemManager.ShowMessageBox("There is an unexpected error: " + ex.Message, "Error", 3);
        }
    }

但是上面的代码报错了:

A generic error occured in GDI+

但是一旦我把保存的图片改成了这样:

bitmap.Save("D:/Test/Screenshot.jpg", ImageFormat.Jpeg);

抓图成功

我的问题是:保存的图片不能添加日期和时间吗?

所以格式是这样的:

Screenshot - 21/01/2015 -.jpg

如有任何帮助,我们将不胜感激!

谢谢

Bitmap.Save() 不构建子目录,这就是您收到错误的原因。

当您将位图保存为 "Screenshot - 21/01/2015 -.jpg" 时,它会假定 / 是目录分隔符,并会尝试相应地构建路径。

一个简单的方法是用其他字符构造日期时间,例如 -