图片压缩并上传oss

# -*- coding: utf-8 -*-
from io import BytesIO
from PIL import Image
import requests
import math
import json
import oss2
import uuid
import logging
import time
import _thread


logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename='imagePillow.log',
                    filemode='w')

newPath='/Users/lvdapeng/PycharmProjects/dataProcessing/image_pillow/images/'
bash_path='/Users/lvdapeng/PycharmProjects/dataProcessing/image_pillow/directory/err_fail.json'

auth = oss2.Auth('*******', '************')
# Endpoint以杭州为例,其它Region请按实际情况填写。
bucket = oss2.Bucket(auth, 'http://oss-cn-shanghai.aliyuncs.com', '*****')
bucketname='*******/'
headers = {"content-type": "application/json"}

def get_imageUrl():
    file = open(bash_path, 'r')
    count = 0
    for line in file.readlines():
        json_line = json.loads(line)
        #print(json_line['picName'])
        count += 1
        #line=line.strip("\n")
        if count > 500:
            break
        get_ImageSize(json_line['picName'],json_line)

def get_ImageSize(line,msg):
    try:
        response = requests.get("https:"+line)
        #response = requests.get("https://img.alicdn.com/imgextra/T1T94dFxRhXXXXXXXX_!!0-item_pic.jpg")
        image = Image.open(BytesIO(response.content), 'r')
        print(image.size)
        # print(image.width)  # 长度
        # print(image.height)  # 宽度
        #print(image.format)  # 格式

        if image.width>800 and image.height>800 :
            w, h = 800, 800  # 去掉浮点,防报错
            img = image.resize((w, h), Image.ANTIALIAS)
            uid = str(uuid.uuid1())
            imaName = ''.join(uid.split('-'))
            img.save(newPath+imaName+"."+image.format, optimize=True, quality=85)  # 质量为85效果最好
            # 上传本地文件
            res = bucket.put_object_from_file(bucketname+imaName+"."+image.format, newPath+imaName+"."+image.format)
            logging.info('Thread:(%d) msg:%s Code:%d ImaName:%s s\n' % (_thread.get_ident(), msg, res.status, imaName + "." + image.format))

        elif image.width>800 and image.height<800:
            w, h = math.trunc(800), math.trunc(800/image.width * image.height) #去掉浮点,防报错
            img = image.resize((w, h), Image.ANTIALIAS)
            uid = str(uuid.uuid1())
            imaName = ''.join(uid.split('-'))
            img.save(newPath+imaName+"."+image.format, optimize=True, quality=85)  # 质量为85效果最好
            res = bucket.put_object_from_file(bucketname + imaName + "." + image.format, newPath + imaName + "." + image.format)
            logging.info('Thread:(%d) msg:%s Code:%d ImaName:%s s\n' % (_thread.get_ident(), msg, res.status, imaName + "." + image.format))

        elif image.width<800 and image.height>800:
            w, h = math.trunc(800 / image.height * image.width),math.trunc(800)   # 去掉浮点,防报错
            img = image.resize((w, h), Image.ANTIALIAS)
            uid = str(uuid.uuid1())
            imaName = ''.join(uid.split('-'))
            img.save(newPath+imaName+"."+image.format, optimize=True, quality=85)  # 质量为85效果最好
            res = bucket.put_object_from_file(bucketname + imaName + "." + image.format, newPath + imaName + "." + image.format)
            logging.info('Thread:(%d) msg:%s Code:%d ImaName:%s s\n' % (_thread.get_ident(), msg, res.status, imaName + "." + image.format))
        else:
            #上传网络流
            input = requests.get("https:"+line)
            uid = str(uuid.uuid1())
            imaName = ''.join(uid.split('-'))
            res = bucket.put_object(bucketname+imaName+"."+image.format,input)

            logging.info('Thread:(%d) msg:%s Code:%d ImaName:%s s\n' % (_thread.get_ident(), msg, res.status, imaName + "." + image.format))

    except Exception as e:
        logging.info('Thread:(%d) msg:%s Error:%s\n'
                     % (_thread.get_ident(), msg, e))


if __name__=='__main__':
    get_imageUrl()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值