Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

c# - How can I get .NET to save this 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:UserssamDesktopS
ourceConsoleApplication20ConsoleApplication20Program.cs:line 16

This issue is reproducible on Windows 7.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This seems to work:

    using (Image image = Image.FromFile(@"c:dumpmyimage.jpg"))
    using (Image clone = new Bitmap(image))
    {
        clone.Save(@"c:dumpmyimage2.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:dumpmyimage.jpg"))
    using (Image clone = new Bitmap(image,
        new Size(image.Size.Width / 2, image.Size.Height / 2)))
    {

        clone.Save(@"c:dumpmyimage2.jpg", ImageFormat.Jpeg);
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...