Handling Corrupted JPEGs in C#

Posted by ddango on Stack Overflow See other posts from Stack Overflow or by ddango
Published on 2010-03-19T19:04:57Z Indexed on 2010/03/19 19:21 UTC
Read the original article Hit count: 225

We have a process that pulls images from a remote server. Most of the time, we're good to go, the images are valid, we don't timeout, etc. However, every once and awhile we see this error similar to this:

Unhandled Exception: System.Runtime.InteropServices.ExternalException: A generic
 error occurred in GDI+.
   at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderPa
rameters encoderParams)
   at ConsoleApplication1.Program.Main(String[] args) in C:\images\ConsoleApplic
ation1\ConsoleApplication1\Program.cs:line 24

After not being able to reproduce it locally, we looked closer at the image, and realized that there were artifacts, making us suspect corruption.

Created an ugly little unit test with only the image in question, and was unable to reproduce the error on Windows 7 as was expected. But after running our unit test on Windows Server 2008, we see this error every time.

Is there a way to specify non-strictness for jpegs when writing them? Some sort of check/fix we can use?

Unit test snippet:

 var r = ReadFile("C:\\images\\ConsoleApplication1\\test.jpg");

        using (var imgStream = new MemoryStream(r))
        {
            using (var ms = new MemoryStream())
            {
                var guid = Guid.NewGuid();
                var fileName = "C:\\images\\ConsoleApplication1\\t" + guid + ".jpg";
                Image.FromStream(imgStream).Save(ms, ImageFormat.Jpeg);
                using (FileStream fs = File.Create(fileName))
                {
                    fs.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
                }
            }

        }

© Stack Overflow or respective owner

Related posts about c#

Related posts about jpeg