# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import io
import uuid

import qiniu
from PIL import Image
from django.conf import settings
from qiniu import etag

url1 = 'http://7u2iif.com1.z0.glb.clouddn.com'
q = qiniu.Auth(settings.QINIU_ACCESS_KEY, settings.QINIU_SECRET_KEY)


def upload(img):
    _img = img.read()
    size = len(_img) / (1024 * 1024)#上传图片的大小 M单位
    # print(size)
    image = Image.open(io.BytesIO(_img))
    # key = str(uuid.uuid1()).replace('-', '') + '.' + image.format
    key = str(uuid.uuid1()).replace('-', '')

    name = 'upfile.{0}'.format(image.format) #获取图片后缀（图片格式）
    # print key
    
    if size > 1:
        x, y = image.size
        im = image.resize((int(x / 1.73), int(y / 1.73)), Image.ANTIALIAS) #等比例压缩 1.73 倍
        print('yasuo')
    else:
        print('buyasuo')
        im = image
    
    # im = image
    
    im.save(settings.MEDIA_ROOT + "/"+ name) #在根目录有个media文件
    path = settings.MEDIA_ROOT + "/" + name
    # print path
    
    try:
        token = q.upload_token(settings.QINIU_BUCKET_NAME, key, 3600,)
        # print token
        ret, info = qiniu.put_file(token, key, path)
        # print ret
        # print info
    except Exception as e:
        print(e)

    url = 'http://7u2iif.com1.z0.glb.clouddn.com/{}'.format(key)

    return url