ZCoder
ZCoder

Reputation: 2349

Getting Error when to save image bitmap A generic error occurred in GDI+

My code is given below what i am trying to do is, getting an image from project folder and then adding some text on the image and then save it to the same folder.

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

Upvotes: 0

Views: 319

Answers (1)

Joel Legaspi Enriquez
Joel Legaspi Enriquez

Reputation: 1236

I think what happen is you are trying to overwrite an image file that are currently opened:

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

What you can do is make a separate instance of the bitmap, close the source, before saving it to the same file.

Here's a code that you can refer to:

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

Upvotes: 2

Related Questions