Python 图像文件压缩,使用PIL库对图像进行等比例压缩。


题目

图像文件压缩。使用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)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

运行后效果

Python 图像文件压缩,使用PIL库对图像进行等比例压缩。_文件大小

Python 图像文件压缩,使用PIL库对图像进行等比例压缩。_python_02


posted @ 2023-04-22 08:08  繁依Fanyi  阅读(5)  评论(0)    收藏  举报  来源