kiriti
kiriti

Reputation: 45

Save the JPG file, A generic error occurred in GDI+

I am trying to save a JPEG image, I am getting the error : "A generic error occurred in GDI+"
I have tried the following code:

Bitmap b = new Bitmap(m_image.Width, m_image.Height);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;

g.DrawImage(m_image, 0, 0, m_image.Width, m_image.Height);
g.Dispose();

Image img1 = (Image)b;
img1.Save(Filename, ImageFormat.Jpeg);
m_image.Save(Filename, ImageFormat.Jpeg);

or

m_image.save(filename, ImaheFormat.Jpeg);

Upvotes: 0

Views: 4727

Answers (2)

Razack
Razack

Reputation: 1896

change the saving files suppose Filename = "c:\1.jpg";

img1.Save("c:\2.jpg", ImageFormat.Jpeg); m_image.Save("c:\3.jpg", ImageFormat.Jpeg); make sure that you have write permission.

I have the following example running perfect

 Image m_image = Image.FromFile(Filename);
            Bitmap b = new Bitmap(m_image.Width, m_image.Height);
            Graphics g = Graphics.FromImage((Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(m_image, 0, 0, m_image.Width, m_image.Height);

            Image img1 = (Image)b;
            img1.Save("C:\\1.jpg", ImageFormat.Jpeg);
            m_image.Save("C:\\2.jpg", ImageFormat.Jpeg);

Upvotes: 0

Dirk
Dirk

Reputation: 10968

According to the MSDN documention for Image.FromFile this method locks the file.

The file remains locked until the Image is disposed.

So if you use something like this

var image = Image.Load(fileName);
// ...
image.Save(fileName)

it will throw an exception because the file is still locked.

You can solve this by not loading the image using this method but rather use one of the overloads taking a Stream parameter:

Image image;
using (var stream = File.OpenRead(fileName))
{
    image = Image.FromStream(stream);
}
// ...
image.Save(fileName);

I didn't have any problems using the code above but the documentation for Image.FromStream says that

You must keep the stream open for the lifetime of the Image.

If you experience any problems you could load the file into a MemoryStream and keep that open.

Upvotes: 2

Related Questions