简体   繁体   中英

How to programmatically detect if a png file is corrupted?

I have written a code that is saving some bitmaps in png format (using bitmap.Save() method). However for some unknown reason some of the images are saved as corrupted pngs so Photoshop cannot open them.

I need to detect these pngs in my code rather than opening them one by one in the Photoshop.

is there any way that I can read the created png and check if it is corrupted?

Are you making sure to close your stream properly when you are done? I think it's extremely unlikely that a Bitmap.Save() would result in a corrupted PNG or that Photoshop couldn't read any PNG created by .NET.

The easiest thing to try is to immediately load it again in .NET. I would try to get to the bottom of why this is happening -- what is specifically corrupt about it?

尝试将文件读回C#,并捕获相应的异常,即出现错误(尽管您未指定损坏的形式-例如,空白文件并没有真正损坏,只是空白!)

我将尝试读取文件,然后检查标题并查看是否存在所有必需的“块”(IHDR,PLTE,IDAT和IEND)并包含合理的数据。

Image.FromFile will throw an OutOfMemoryException if it cannot understand the format of the file. This strikes me as kind of an odd choice for an exception, but both empirically testing and the documentation agree that this is the exception it throws.

See Image.FromFile Method (String) on the MSDN .

The PNG format allows different compression, filtering, and interlacing methods. Do you have an older version of Photoshop that is perhaps not aware of newer methods?

It might be useful to examine the headers of two PNG files: One that does load, and one that doesn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM