本篇文章小编给大家分享一下python批量压缩图像代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
操作步骤
要求
默认是使用的是Anaconda的环境。
将所有要压缩的图片都放在一个文件夹下,然后每个图片的格式只能是下面三种:png,jpg, jpeg。如果是PNG也不行。因为PNG是png的大写。
代码中设置的图像的压缩后的大小是512KB,那么你可以设置代码中的target_size为500,只要比512KB小就行了。
然后把我的代码从GitHub上下载下来。代码链接为:https://github.c**o*m/yuanzhoulvpi2017/tiny_python/blob/main/image_compression/ic.py
步骤
我这里把所有图片都放在了一个文件夹里面,文件夹名称为历史截图。然后我的这个历史截图和ic.py代码都放在了little_code文件夹中。
在little_code文件夹下,打开终端。
直接运行的脚本:
python ic.py xxx_文件夹
等待一会,就会将整个文件夹下的所有图片都转化好了。
完整代码:
如果上不去GitHub的话,我直接把代码放在这里,保存为一个python文件即可。比如保存的文件名为:ic.py
from PIL import Image
from glob import glob
import os
from tqdm import tqdm
import shutil
import sys
from itertools import chain
from multiprocessing import Pool
# image_dir = "image_dir"
template_dir = 'template'
output_dir = 'output'
error_dir = 'error'
def clean_dir(dir_name):
if os.path.exists(dir_name):
shutil.rmtree(dir_name)
os.makedirs(dir_name)
else:
os.makedirs(dir_name)
# image_file_list = glob(f"{image_dir}/*")
# image_file_list
def imagesize(filepath):
"""
获得文件的磁盘大小
:param filepath:
:return:
"""
return os.path.getsize(filepath) / 1024
def compress_image(image_path):
raw_image = Image.open(image_path)
temp_image_name = image_path.split(os.sep)[-1]
template_image = os.path.join(template_dir, temp_image_name)
output_image = os.path.join(output_dir, temp_image_name)
error_image = os.path.join(error_dir, temp_image_name)
target_size = 500 # kb
try:
if imagesize(image_path) target_size:
template_iamge2 = Image.open(template_image)
width_2, height_2 = template_iamge2.size
template_iamge2.resize((int(width_2 * 0.9), int(height_2 * 0.9)), Image.ANTIALIAS).save(template_image)
shutil.copyfile(template_image, output_image)
except Exception as e:
shutil.copyfile(image_path, error_image)
print(f'文件保存失败: {image_path}')
# print(e)
if __name__ == '__main__':
# 批量创建文件夹
[clean_dir(i) for i in [template_dir, output_dir, error_dir]]
image_dir = sys.argv[1]
image_file_list = list(chain(*[glob(os.path.join(image_dir, i)) for i in ['*.png', '*.jpg', '*.jpeg']]))
# for temp_image_path in tqdm(image_file_list):
# compress_image(temp_image_path)
print(f'nn文件保存父目录: {os.getcwd()}n'
f'输出文件位置:{os.path.join(os.getcwd(), output_dir)}nn')
# parallel
P = Pool(processes=10)
pbar = tqdm(total=len(image_file_list))
res_temp = [P.apply_async(func=compress_image, args=(i,), callback=lambda _: pbar.update(1)) for i in
image_file_list]
_ = [res.get() for res in res_temp]
附:批量将图片的大小设置为指定大小
import os
from PIL import Image
# 源目录
project_dir = os.path.dirname(os.path.abspath(__file__))
input = os.path.join(project_dir, 'src')
# 输出目录
output = os.path.join(project_dir, 'dest')
def modify():
# 切换目录
os.chdir(input)
# 遍历目录下所有的文件
for image_name in os.listdir(os.getcwd()):
print(image_name)
im = Image.open(os.path.join(input, image_name))
im.thumbnail((128, 128))
im.save(os.path.join(output, image_name))
if __name__ == '__main__':
modify()