兩行 Python 代碼,精準(zhǔn)識(shí)別一張圖片的格式


https://www.kingname.info/xx/yy/zz,在 URL 中沒有顯示圖片的格式。那么,當(dāng)你用爬蟲把這個(gè)圖片下載下來以后,應(yīng)該怎么保存呢?python3 -m pip install pillow
PIL導(dǎo)入圖片處理的模塊Image:from PIL import Image
img = Image.open('/Users/kingname/Dropbox/50e452c3504a6.jpg')
print(img.format)

Image.open()接收的參數(shù)是一個(gè)文件地址。我們需要讓 Pillow 從內(nèi)存中讀取圖片數(shù)據(jù),生成圖片對象以后,查看它的.format屬性。io模塊,把二進(jìn)制的數(shù)據(jù)包裝成一個(gè)假的二進(jìn)制文件句柄:import io
import base64
from PIL import Image
img_base64 = '圖片對應(yīng)的 base64'
img_byte = base64.b64decode(img_base64.encode())
img_io = io.BytesIO(img_byte)
img = Image.open(img_io)
print(img.format)
評(píng)論
圖片
表情
