这里介绍python处理图片,在接收前端传过来的base64码时应注意去掉前面那一段base标识,(以时间戳命名保证图片不会重名导致覆盖)
import time,base64
# base64转图片
def decode_base64(strs:str):
# 这里需要去除前端传过来的data:image/jpeg;base64,
index = strs.find('base64')
new_str = strs[index+7:]
# 以时间戳命名
img_date = time.localtime(time.time())
img_decode_time = time.strftime('%Y%m%d%H%M',img_date)
img_data = base64.b64decode(new_str)
with open(img_decode_time+'.jpg', 'wb') as file:
file.write(img_data)
# 图片转base64(但是一般在接口中给出的都是图片地址,不会直接传base64编码)
def encode_base64(path:str):
with open(path, 'rb') as file:
base64_data = base64.b64encode(file.read())
return base64_data
网友评论