上周有個(gè)需求需要把爬取的圖片上傳到Magento后臺服務(wù)器经柴,并顯式聲明文件格式,例如:
"type": "image/jpeg",
"name": "abc.jpg",
'base64_encoded_data': "b64encoding_string"
上傳過程中服務(wù)器會根據(jù)圖片的二進(jìn)制頭來驗(yàn)證格式间驮,如果與type聲明的格式不一致或者此格式(比如:webp
)服務(wù)器不支持,就會拋出不匹配異常马昨。
我面臨兩個(gè)問題:
- 下載圖片的url文件名后綴和圖片真實(shí)格式并不一樣,比如下載下來的是abc.jpg但通過二進(jìn)制打開發(fā)現(xiàn)圖片格式其實(shí)是webp杨帽。
- 下載后上傳前我并不知道文件是什么格式的摄乒。
所以我需要工具解決圖片轉(zhuǎn)碼和圖片識別的問題悠反,這里總結(jié)一下用到的工具和步驟:
import hashlib
import base64
import requests
import os, time
from PIL import Image
# 指定圖片下載與轉(zhuǎn)碼路徑
basedir = os.path.abspath(os.path.dirname(__name__))
image_path = os.path.join(basedir, 'static')
def image_download(image_link):
headers = {
'Cache-Control': "no-cache",
'user-agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36",
}
# 用url的md5指紋作為文件名
image_guid = hashlib.md5(image_link.encode('utf-8')).hexdigest()
filename = os.path.join(image_path, image_guid)
if os.path.exists(filename):
image = Image.open(filename)
image_format = image.format
else:
while True:
response = requests.request("GET", image_link, headers=headers)
if len(response.content) == int(response.headers['Content-Length']):
with open(filename, 'wb') as f:
f.write(response.content)
# 讀取文件二進(jìn)制格式
image = Image.open(filename)
image_format = image.format
# 如果是服務(wù)器不支持的webp格式轉(zhuǎn)為jpeg格式
if image_format == 'WEBP':
image.save(filename, 'JPEG')
image_format = 'JPEG'
break
else:
time.sleep(1)
# 返回文件名與圖片格式
return image_guid, image_format
# base64轉(zhuǎn)碼生成body體用于上傳
def image_read_base64(image):
filename = os.path.join(image_path, image)
with open(filename, 'rb') as f:
b64encoding = base64.b64encode(f.read())
return b64encoding.decode()