版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tao_627/article/details/85196761
需求
有时候自媒体创作写稿时难免遇到大规模压缩某个文件夹内的图片的情况,通常我们可以使用一些批量压缩的工具来处理,但我觉得,这是小白的做法,对于我们这些经验丰富的老司机来说,使用代码来处理,将是一件高效而且高逼格的事情。使用PIL中的Image模块,就能很快地完成这项工作。
准备
我的电脑图片文件夹中有一个壁纸文件夹"win8壁纸",都是分辨率超过1080P的大图,我将使用python代码将它们中超过1MB的图片批量等比例压缩一下
代码
#!/usr/bin/env python
#encoding: utf-8
#description: 压缩指定目录下面的图片到指定尺寸(1080P),实测比较靠谱
#date: 2018-12-19
from PIL import Image
from glob import glob
import os
import math
#输入参数说明:
#src_dir: 源图片所在目录
#dst_dir: 输出图片所在目录
#fn: 待处理的图片文件名
#thrd: 图片字节大小的阈值,超过就会等比例缩放处理
def resize_image(src_dir, dst_dir, fn, thrd):
filename = os.path.join(src_dir, os.path.basename(fn))
with Image.open(filename) as img:
#获取图片高度和宽度
width, height = img.size
if width >= height:
new_width = int(math.sqrt(thrd/2))
new_height = int(new_width * height * 1.0 / width)
else:
new_height = int(math.sqrt(thrd/2))
new_width = int(new_height * width * 1.0 / height)
#调整图片到新的尺寸(兼容各种尺寸大小)
#强调是PIL带ANTIALIAS滤镜缩放效果
resized_img = img.resize((new_width, new_height), Image.ANTIALIAS)
out_fn = filename.replace(src_dir, dst_dir)
#将调整后的文件存放到指定目录下面
resized_img.save(out_fn)
def resize_images(src_dir, dst_dir, thrd):
filenames = glob('{}/*'.format(src_dir))
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for filename in filenames:
#获取图片大小
filesize = os.path.getsize(filename)
print('filename:%s, size:%d' %(filename, filesize))
if filesize >= threshold:
resize_image(src_dir, dst_dir, filename, thrd)
if __name__ == '__main__':
source_dir = '/home/taoyx/图片/win8壁纸/'
target_dir = '/home/taoyx/图片/img_test/'
threshold = 1*1024*1024
resize_images(source_dir, target_dir, threshold)
效果
执行上述脚本
python imgs_resize.py
得到如下效果