我的代码在下面给出了我想要做的是,从项目文件夹中获取图像,然后在图像上添加一些文本,然后将其保存到同一文件夹。
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
答案 0 :(得分:2)
我认为您正在尝试覆盖当前打开的图像文件:
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