如何检查文件是否是有效的图像文件? [英] How to check if a file is a valid image file?

查看:158
本文介绍了如何检查文件是否是有效的图像文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用PIL。

I am currently using PIL.

from PIL import Image
try:
    im=Image.open(filename)
    # do stuff
except IOError:
    # filename not an image file

然而,尽管这足以涵盖大多数情况,但未检测到某些图像文件,如xcf,svg和psd。 Psd文件抛出OverflowError异常。

However, while this sufficiently covers most cases, some image files like, xcf, svg and psd are not being detected. Psd files throws an OverflowError exception.

有没有我可以包含它们?

Is there someway I could include them as well?

推荐答案

很多时候,前几对字符将是各种文件格式的幻数。除了上面的异常检查之外,您还可以检查这一点。

A lot of times the first couple chars will be a magic number for various file formats. You could check for this in addition to your exception checking above.

这篇关于如何检查文件是否是有效的图像文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆