Python作为一种强大的编程语言,提供了多种库来处理图片,包括PIL(Python Imaging Library)和Pillow。这些库使得我们能够轻松地对图片进行各种操作,包括批量压缩。
OS 模块:提供了与操作系统交互的接口。
PIL(Python Imaging Library,但通常称为Pillow): 一个图像处理库,用于打开、操作和保存多种不同的图像文件格式。
使用Python批量压缩图片大小的优势在于:
- 自动化:通过编写脚本,我们可以自动处理大量的图片,而无需手动进行每一张图片的压缩。
- 灵活性:Python提供了多种压缩方法,我们可以根据需要选择不同的压缩算法和参数,以达到最佳的压缩效果。
- 跨平台:Python可以在多种操作系统上运行,这意味着我们可以在任何支持Python的平台上进行图片压缩。
- 节省时间:批量压缩可以大大减少我们的工作量,并节省大量的时间。
具体代码如下:
import os
from PIL import Image
def compress(src_path, dst_path, compress_rate=0.5):
img = Image.open(src_path)
w = int(img.size[0] * compress_rate)
h = int(img.size[1] * compress_rate)
img_resize = img.resize((w, h))
img_resize.save(dst_path)
if __name__ == "__main__":
src_dir = 'E:\\ceshi\\图片' # 源路径
dst_dir = 'E:\\ceshi\\压缩后图片' #目的路径
if not os.path.exists(dst_dir):
os.mkdir(dst_dir)
for filename in os.listdir(src_dir):
img_path = os.path.join(src_dir, filename)
new_img_path = os.path.join(dst_dir, filename)
compress(img_path, new_img_path, 0.3)
使用Python批量压缩图片大小是一个非常实用的功能,它可以帮助我们更好地管理和优化图片资源。无论是在个人还是商业应用中,这都是一个非常有用的工具。