python获取图片类型
- imghdr
python有一个自带的函数,可以获取图片类型imghdr.what(f, h=None)
f可以是一个文件路径,也可以是一个打开的文件类型
例如:import imghdr
imghdr.what('path/to/ur/image')
结果等价于import imghdr
f = open('path/to/ur/image')
imghdr.what(f.read())
- Imgae
from PIL import Image
img = Image.open('path/to/ur/image')
filetype = img.format()
- 获取base64编码图片的格式
如果我们获得的是一个base64编码的图片,想要得到他的图片格式,需要对base64编码图片做一些转变
传过来的图片import base64
f = open('path/to/ur/image')
img_b64 = base64.b64encode(f.read())
利用imghdr获得图片格式import imghdr
img = base64.b64decode(img_b64)
imghdr.what(None,img)
利用Image获得图片格式import io
from PIL import Image
img_bytes = io.BytesIO(base64.b64decode(img_b64))
img = Image.open(img_bytes)
filetype = img.format()
原文地址:https://www.cnblogs.com/laozhanghahaha/p/15002147.html