python压缩图片大小

from PIL import Image
import os

# 获取文件名
file_names = os.listdir("./")
#print(file_names)
# 文件名拼接路径
#file_list = [os.path.join("./",file) for file in file_names]
file_list = ["./初成.png"]
#print(file_list)
for pic_file_path in file_list:
    if os.path.isfile(pic_file_path):
        try:
            # 打开原图片缩小后保存,可以用if srcFile.endswith(".jpg")或者split,splitext等函数等针对特定文件压缩
            sImg = Image.open(pic_file_path)
            w, h = sImg.size
            
            print(pic_file_path,"++++++",sImg.size)
            if w < 700 or h < 400:
                continue
            dImg = sImg.resize((int(w / 2), int(h / 2)), Image.ANTIALIAS)  # 设置压缩尺寸和选项,注意尺寸要用括号
            dImg.save(pic_file_path)  # 也可以用srcFile原路径保存,或者更改后缀保存,save这个函数后面可以加压缩编码选项JPEG之类的
            print(pic_file_path + "压缩成功!")
        except Exception:
            print(pic_file_path + "压缩失败!")
pip install -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com pillow

 

posted @ 2022-06-30 10:34  chenjianwen  阅读(833)  评论(0编辑  收藏  举报