代码拉取完成,页面将自动刷新
# -*- coding: utf-8 -*-
# flake8: noqa
import configparser
import logging
import shutil
import time
import os
from PIL import Image
from shutil import copyfile
from qiniu import Auth, put_file, etag
def get_size(file):
# 获取文件大小:KB
size = os.path.getsize(file)
return int(size / 1024)
def compress_image(infile, outfile='', mb=3000, 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:
copyfile(infile, outfile)
return infile
copyfile(infile, outfile)
while o_size > mb:
im = Image.open(outfile)
im = im.convert('RGB')
im.save(outfile, quality=quality)
if quality - step < 0:
break
quality -= step
o_size = get_size(outfile)
return outfile, get_size(outfile)
if __name__ == '__main__':
# 日志相关配置
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
logging.basicConfig(filename="log/system.log", level=logging.DEBUG, format=LOG_FORMAT, datefmt=DATE_FORMAT)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter(LOG_FORMAT)
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
# config信息配置
conf = configparser.ConfigParser()
conf.read("config.ini", encoding="utf-8")
# 获取基本信息
access_key = conf.get("info", "access_key")
secret_key = conf.get("info", "secret_key")
bucket_name = conf.get("info", "bucket_name")
host = conf.get("info", "host")
zip_max = conf.get("info", "zip_max")
# 七牛云构建鉴权对象
q = Auth(access_key, secret_key)
print("╔═════════════════════════════════╗")
print("║ QiNiu-PictureHostTool by NC ║")
print("╚═════════════════════════════════╝")
while True:
inFilePath = input("请输入需要上传的文件地址:")
suffix = os.path.splitext(inFilePath)[-1]
timeStamp = str(int(round(time.time() * 1000)))
if suffix in ('.png', '.PNG'):
logging.info("当前文件为.png文件,将会转为.jpg文件......")
logging.info("文件压缩前大小:" + str(get_size(inFilePath)) + "KB")
compress_image(inFilePath, outfile="./temp/" + timeStamp + '.jpg', mb=int(zip_max), step=10, quality=80)
logging.info("压缩完成!")
logging.info("文件压缩后大小:" + str(get_size("./temp/" + timeStamp + '.jpg')) + "KB")
# 生成上传 Token,可以指定过期时间等
token = q.upload_token(bucket_name, timeStamp + '.jpg', 3600)
ret, info = put_file(token, timeStamp + '.jpg', "./temp/" + timeStamp + '.jpg')
logging.info("Hash:" + ret["hash"])
logging.info("key:" + ret["key"])
logging.info("外链:"+host + timeStamp + '.jpg')
print("============================================")
print("外链: "+host + timeStamp + '.jpg')
print("============================================")
# 清空临时目录
shutil.rmtree("./temp")
os.mkdir("./temp")
exit()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。