1 Star 0 Fork 0

夜猫/七牛云图床上传工具

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
main.py 3.50 KB
一键复制 编辑 原始数据 按行查看 历史
夜猫 提交于 2021-07-01 22:32 . 项目主体
# -*- 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()
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/Nightcats/QiNiuPicHostTool.git
git@gitee.com:Nightcats/QiNiuPicHostTool.git
Nightcats
QiNiuPicHostTool
七牛云图床上传工具
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385