• 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)
    
    
  • 相关阅读:
    [哈希][倍增] Jzoj P5856 01串
    [exgcd] Jzoj P5855 吃蛋糕
    [折半搜索][分治][二分] Jzoj P5851 f
    [lca][主席树] Jzoj P5850 e
    [二分][树状数组] Jzoj P5849 d
    [容斥] Jzoj P5843 b
    [前缀和][枚举] Jzoj P5842 a
    [平衡规划][模拟][前缀和] Jzoj P4724 斐波那契
    [spfa] Jzoj P4722 跳楼机
    [模拟] Jzoj P2499 东风谷早苗
  • 原文地址:https://www.cnblogs.com/gongcheng-/p/12531159.html
Copyright © 2020-2023  润新知