开发者

Handling Corrupted JPEGs in C#

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 200开发者_如何转开发8, 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);
                }
            }

        }


AFAIK, no, there is no way to ask GDI+ to be more lenient when decoding JPG files. In any application where you have consumers uploading arbitrary JPG files you will see a number of these Generic error in GDI+ exceptions being thrown all the time. You could try using WPF to read your image instead, but I suspect it too will object to corrupt images.


Maybe it's not answer to your direct question, but why would't you pull image and its md5 (or any other hash) that can verify correctnes of this image?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜