【问题标题】:Getting Error when to save image bitmap A generic error occurred in GDI+保存图像位图时出现错误 GDI+ 中发生一般错误
【发布时间】:2015-08-26 02:23:26
【问题描述】:

下面给出了我的代码,我想要做的是,从项目文件夹中获取图像,然后在图像上添加一些文本,然后将其保存到同一个文件夹中。

string firstText = "Hello";
string secondText = "World";

PointF firstLocation = new PointF(10f, 10f);
PointF secondLocation = new PointF(10f, 50f);
var imageFilePath = Server.MapPath("~/Images/" + "a.png");

Bitmap bitmap = (Bitmap)Image.FromFile(imageFilePath);//load the image file

using (Graphics graphics = Graphics.FromImage(bitmap))
{
    using (Font arialFont = new Font("Arial", 10))
    {
        graphics.DrawString(firstText, arialFont, Brushes.Blue, firstLocation);
        graphics.DrawString(secondText, arialFont, Brushes.Red, secondLocation);
    }
}

bitmap.Save(imageFilePath);//save the image file

【问题讨论】:

  • 你遇到了什么错误?
  • 我刚刚做了这个和它的工作 bitmap.Save(imageFilePath+".jpg");//保存图像文件

标签: c# bitmap bitmapimage


【解决方案1】:

我认为您正在尝试覆盖当前打开的图像文件:

Bitmap bitmap = (Bitmap)Image.FromFile(imageFilePath);//load the image file

您可以做一个单独的bitmap 实例,关闭源代码,然后将其保存到同一个文件中。

这是一个你可以参考的代码:

Bitmap bitmap = (Bitmap)Image.FromFile(imageFilePath);
Bitmap temp = new Bitmap(bitmap.Width, bitmap.Height, bitmap.PixelFormat); //Create temporary bitmap
using (Graphics graphics = Graphics.FromImage(temp))
{
    using (Font arialFont = new Font("Arial", 10))
    {
        //Copy source image first
        graphics.DrawImage(bitmap, new Rectangle(0, 0, temp.Width, temp.Height), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
        graphics.DrawString(firstText, arialFont, Brushes.Blue, firstLocation);
        graphics.DrawString(secondText, arialFont, Brushes.Red, secondLocation);
    }
}
bitmap.Dispose(); //Dispose your source image
temp.Save(imageFilePath);//save the image file
temp.Dispose(); //Dispose temp after saving

【讨论】:

  • 对...请参阅Image.FromFile() 的文档:在释放图像之前,文件保持锁定状态。 因此,您需要先释放实例才能释放文件你试图覆盖它。
  • 请注意,添加.jpg 将更改目标文件的文件名,因此在文件系统上创建一个新文件,a.png 现在变为a.png.jpg。这可能不是您想要的行为。
猜你喜欢
  • 1970-01-01
  • 2013-09-26
  • 1970-01-01
  • 1970-01-01
  • 2010-12-19
  • 2015-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多