python - 如何检查文件是否是有效的图像文件?

我目前正在使用 PIL。

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

然而,虽然这足以涵盖大多数情况,但某些图像文件(如 xcf、svg 和 psd)并未被检测到。 Psd 文件会引发 OverflowError 异常。

有什么方法可以让我也包含它们吗?

最佳答案

我刚刚找到了内置 imghdr模块。来自python文档:

The imghdr module determines the type of image contained in a file or byte stream.

这就是它的工作原理:

>>> import imghdr
>>> imghdr.what('/tmp/bass')
'gif'

使用模块比重新实现类似功能要好得多

更新: imghdr is deprecated as of python 3.11

https://stackoverflow.com/questions/889333/

相关文章:

python - 如何绘制正态分布

python - 来自 os.listdir() 的非字母数字列表顺序

python - 非 ASCII 字符的语法错误

python - “模块”没有属性 'urlencode'

python - 在 CentOS 中安装 python 2.6

python - urllib2.HTTPError : HTTP Error 403: Forbi

python - SQLAlchemy ORM 转换为 pandas DataFrame

python - 使用 PyInstaller (--onefile) 捆绑数据文件

python - 为什么循环导入似乎在调用堆栈中更靠前,但在更靠下的位置引发 ImportError

python - 如何删除字符串中的前导零和尾随零? Python