python使用bytesIO 实现图片在内存中压缩上传阿里云
需要在从阿里云获取图片,进行图像处理,然后将生成图压缩到500kb以下上传到oss,不进行文件本地操作
但是图片压缩需要用到 Image.save 函数,需要传入一个本地路径,这里可以使用bytesIO解决,
不断修改 Image.save 的参数 quality 改变 生成图的大小直到小于 500kb
import oss2
import PIL
class OssFile(object):
def __init__(self):
self.auth = oss2.Auth(config.OSS_ACCESS_KEY_ID, config.OSS_ACCESS_KEY_SECRET)
self.bucket = oss2.Bucket(self.auth, config.OSS_END_POINT, config.OSS_BUCKET_NAME)
def put_object(self,ossfile,localfile):
self.bucket.put_object(ossfile,localfile)
def get_oss_file(self,ossfile):
return self.bucket.get_object(ossfile)
if __name__== "__main__":
oss_obj = OssFile()
#image = Image.open(r"test.jpg")
image = oss_obj.get_oss_file("oss_key")
save_quality = 95
query_sum = 0
size = 512000
while True:
img_byte_arr = io.BytesIO()
query_sum += 1
image.save(img_byte_arr, quality=save_quality)
pic_size_bytes = img_byte_arr.tell()
if pic_size_bytes < size :
break
if isinstance(save_quality, int) and query_sum < 90:
save_quality = int(save_quality) - int(query_sum)
continue
else:
break
img_byte_arr = img_byte_arr.getvalue()
oss_obj.put_object("save_path", img_byte_arr)