imghdr模块提供了what()方法,该方法可以推测文件或字节流中的图像的类型。可以识别的图片格式见Python文档。为防止打不开,我把截图放在下面。
imghdr的使用方法比较简单,如下所示。你可以传入一个文件,也可以传入字节流。
import imghdr
# 文件形式
res = imghdr.what("/home/zy/图片/渴望.png")
print(res)
# 字节流形式
import requests
data = requests.get(url="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic16.nipic.com%2F20110722%2F7714743_143330894000_2.jpg&refer=http%3A%2F%2Fpic16.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1639707331&t=2391d95323e25c4a5cfa0f936042d3f3")
res = imghdr.what(None, data.content) # data.content是bytes类型。
print(res)
执行结果如下所示:
png
jpeg