题目
图像文件压缩。使用PIL库对图像进行等比例压缩,无论压缩前文件大小如何,压缩后文件大小小于10KB。
代码
from PIL import Image
import os
from tkinter import filedialog
import tkinter
f_path = filedialog.askopenfilename()
image = Image.open(f_path)
size = os.path.getsize(f_path)/1024
width, height = image.size
while True:
if size>10:
width,height = round(width*0.9), round(height*0.9)
image = image.resize((width,height),Image.ANTIALIAS)
image.save(f_path)
size = os.path.getsize(f_path)/1024
else:
break
str_info = "压缩完成,现在大小是{}KB".format(size)
print(str_info)
运行后效果


这段代码演示了如何利用Python的PIL库对图像进行等比例压缩,目标是使压缩后的文件大小不超过10KB。通过不断调整图像的宽度和高度,应用ANTIALIAS选项保证质量,直到文件大小满足条件。
2221

被折叠的 条评论
为什么被折叠?



