python图片压缩

import requests
from PIL import Image
import os
import flask, json
import random

def get_size(file):
    # 获取文件大小:KB
    size = os.path.getsize(file)
    return size / 1024

def get_outfile(infile, outfile):
    if outfile:
        return outfile
    dir, suffix = os.path.splitext(infile)
    outfile = '{}-out{}'.format(dir, suffix)
    return outfile

def compress_image(infile, outfile='', mb=200, step=10, quality=80):
    """不改变图片尺寸压缩到指定大小
    :param infile: 压缩源文件
    :param outfile: 压缩文件保存地址
    :param mb: 压缩目标,KB
    :param step: 每次调整的压缩比率
    :param quality: 初始压缩比率
    :return: 压缩文件地址,压缩文件大小
    """
    o_size = get_size(infile)
    if o_size <= mb:
        return infile
    outfile = get_outfile(infile, outfile)
    while o_size > mb:
        im = Image.open(infile)
        im.save(outfile, quality=quality)
        if quality - step < 0:
            break
        quality -= step
        o_size = get_size(outfile)
    return outfile, get_size(outfile)


# 创建一个服务,把当前这个python文件当做一个服务
server = flask.Flask(__name__)


# server.route()可以将普通函数转变为服务 登录接口的路径、请求方式
@server.route('/compress', methods=['PUT'])
def compress():
    path = flask.request.values.get('path')
    filename = flask.request.values.get('filename')
    compress_image(path, './'+filename+'.jpg')

    return json.dumps('ok')

if __name__ == '__main__':
    server.run(debug=True, port=5088, host='0.0.0.0')  # 指定端口,host,0.0.0.0代表不管几个网卡,任何ip都可访问

标签

发表评论