我目前正在使用 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/