本帖最后由 元豪 于 2023-5-1 08:35 编辑 import tinify, os, sys
tinify.key = 'key'
houzhui = ['.jpg', '.png', '.webp']
num = 0
s = t1 = t2 = None
ss = []
def printf(ttt):
def func():
ttt(s, t1, t2)
return func
@printf
def ttt(s, t1, t2):
print('({}/{})图片<{}>正在压缩处理中, 请稍后...'.format(t2, t1, s))
kkk = sys.argv
if len(kkk) > 1:
for i in kkk:
if os.path.splitext(i)[1] in houzhui:
img = tinify.from_file('{}{}'.format(os.path.splitext(i)[0], os.path.splitext(i)[1]))
img.to_file('{}{}'.format(os.path.splitext(i)[0] + '_new', os.path.splitext(i)[1]))
num += 1
ss.append(os.path.splitext(i)[0] + os.path.splitext(i)[1])
t1 = num
for i in range(num):
t2 = i + 1
s = ss[i]
ttt()
else:
x = input('请输入需要压缩的图片(回车优化当前文件夹): ')
if not x:
print('开始优化当前文件下所有.jpg/.png/.webp文件')
g = input('请输入尺寸(宽度 高度): ')
if not g:
for i in os.listdir('./'):
hou = os.path.splitext(i)[1]
if hou in houzhui:
img = tinify.from_file('{}{}'.format(os.path.splitext(i)[0], os.path.splitext(i)[1]))
img.to_file('{}{}'.format('new_' + os.path.splitext(i)[0], os.path.splitext(i)[1]))
ss.append(os.path.splitext(i)[0] + os.path.splitext(i)[1])
num += 1
t1 = num
for i in range(num):
s = ss[i]
t2 = i + 1
ttt()
elif '0' in g.split():
w, h = map(int, g.split())
for i in os.listdir('./'):
hou = os.path.splitext(i)[1]
if hou in houzhui:
img = tinify.from_file('{}{}'.format(os.path.splitext(i)[0], os.path.splitext(i)[1]))
if w == 0:
newimg = img.resize(method='scale', height=h)
else:
newimg = img.resize(method='scale', width=w)
newimg.to_file('{}{}'.format('new_' + os.path.splitext(i)[0], os.path.splitext(i)[1]))
ss.append(os.path.splitext(i)[0] + os.path.splitext(i)[1])
num += 1
t1 = num
for i in range(num):
s = ss[i]
t2 = i + 1
ttt()
else:
w, h = map(int, g.split())
for i in os.listdir('./'):
hou = os.path.splitext(i)[1]
if hou in houzhui:
img = tinify.from_file('{}{}'.format(os.path.splitext(i)[0], os.path.splitext(i)[1]))
newimg = img.resize(method='fit', width=w, height=h)
newimg.to_file('{}{}'.format('new_' + os.path.splitext(i)[0], os.path.splitext(i)[1]))
ss.append(os.path.splitext(i)[0] + os.path.splitext(i)[1])
num += 1
t1 = num
for i in range(num):
s = ss[i]
t2 = i + 1
ttt()
else:
g = input('请输入尺寸(宽度 高度): ')
if not g:
img = tinify.from_file('{}{}'.format(os.path.splitext(x)[0], os.path.splitext(x)[1]))
img.to_file('{}{}'.format('new_' + os.path.splitext(x)[0], os.path.splitext(x)[1]))
s = '{}{}'.format(os.path.splitext(x)[0], os.path.splitext(x)[1])
t1 = t2 = 1
ttt()
else:
w, h = map(int, g.split())
img = tinify.from_file('{}{}'.format(os.path.splitext(x)[0], os.path.splitext(x)[1]))
if w and h:
newimg = img.resize(method='fit', width=w, height=h)
elif not w:
newimg = img.resize(method='scale', height=h)
elif not h:
newimg = img.resize(method='scale', width=w)
newimg.to_file('new_{}{}'.format(os.path.splitext(x)[0], os.path.splitext(x)[1]))
s = '{}{}'.format(os.path.splitext(x)[0], os.path.splitext(x)[1])
t1 = 1
t2 = 1
ttt()
print('全部处理完成~')
@小甲鱼 可以把最后一个名额给我吗写了好久 |