zoukankan      html  css  js  c++  java
  • 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)
    
    
  • 相关阅读:
    Web API初印象
    SQL注入总结篇
    Debian Linux 下安装pip3
    DVWA:环境搭建
    AWVS使用手册
    常见的反爬虫和应对方法
    Fiddler抓取手机APP数据包
    爬虫 Scrapy框架 爬取图虫图片并下载
    python 爬虫基础知识(继续补充)
    Python 爬虫 多进程清洗代理
  • 原文地址:https://www.cnblogs.com/gongcheng-/p/12531159.html
Copyright © 2011-2022 走看看