python,图片压缩
转载链接:https://zhuanlan.zhihu.com/p/161274600
from PIL import Image
# 直接打开文件
im = Image.open("test.jpg")
# body转Image
img_body = open("test.jpg", 'rb').read()
im = Image.open(io.BytesIO(img_body))
size = len(img_body)
print("图片: 大小{} byte,{} kb,{} Mb".format(size, size / 1024, size / 1024 / 1024))
print(im.format, im.size, im.mode)
size = (355, 250,)#压缩后图片的大小
new_photo = im.copy()
new_photo.thumbnail(size, resample=Image.ANTIALIAS)
save_args = {'format':im.format}
if im.format=='JPEG':
save_args['quality'] = 85
# 直接保存到本地。
new_photo.save('test1.jpg',**save_args)
# 转成body后保存。
bytes_io = io.BytesIO()
new_photo.save(bytes_io , **save_args)
with open('test2.jpg', 'wb') as f:
f.write(bytes_io .getvalue())