Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get .NET to save this image?

Tags:

c#

.net

image

I have this JPEG image, that opens fine in Picasa, Photoshop, web browser, etc., but in .NET it just refuses to work.

 Image image = Image.FromFile(@"myimage.jpg");
 image.Save(@"myimage2.jpg");
 // ExternalException - A generic error occurred in GDI+.

Is there a way to recover it in .NET so I can work with it (I need to resize it), without fixing the problem at the source?

Full exception details:

source: System.Drawing
type: System.Runtime.InteropServices.ExternalException
message: A generic error occurred in GDI+.
stack trace:
at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
   at System.Drawing.Image.Save(String filename, ImageFormat format)
   at System.Drawing.Image.Save(String filename)
   at ConsoleApplication20.Program.Main(String[] args) in C:\Users\sam\Desktop\S
ource\ConsoleApplication20\ConsoleApplication20\Program.cs:line 16

This issue is reproducible on Windows 7.

like image 362
Sam Saffron Avatar asked Feb 26 '10 08:02

Sam Saffron


People also ask

How do I save an image file?

Save a picture or other image as a separate fileControl-click the illustration that you want to save as a separate image file, and then click Save as Picture. In the Save as type list, select the file format that you want. In the Save As box, type a new name for the picture, or just accept the suggested file name.


2 Answers

This seems to work:

    using (Image image = Image.FromFile(@"c:\dump\myimage.jpg"))
    using (Image clone = new Bitmap(image))
    {
        clone.Save(@"c:\dump\myimage2.jpg", ImageFormat.Jpeg);
    }

image is actually a Bitmap anyway, so it should be similar. Oddly myimage2 is 5k smaller - the joys of jpeg ;-p

A nice thing about this is that you can resize at the same time (your actual intent):

    using (Image image = Image.FromFile(@"c:\dump\myimage.jpg"))
    using (Image clone = new Bitmap(image,
        new Size(image.Size.Width / 2, image.Size.Height / 2)))
    {

        clone.Save(@"c:\dump\myimage2.jpg", ImageFormat.Jpeg);
    }
like image 79
Marc Gravell Avatar answered Nov 02 '22 00:11

Marc Gravell


Try explicitly specifying the format:

using (Image image = Image.FromFile(@"test.jpg"))
{
    image.Save(@"myimage2.gif", ImageFormat.Gif);
}

All ImageFormat.Png, ImageFormat.Bmp and ImageFormat.Gif work fine. ImageFormat.Jpeg throws an exception.

The original image is in the JFIF format as it starts with FF D8 FF E0 bytes.

like image 42
Darin Dimitrov Avatar answered Nov 01 '22 22:11

Darin Dimitrov