Python 官方文档:入门教程 => 点击学习
目录第一种 一:安装包二:导入包三:获取图片文件的大小四:输出文件夹下的文件五:压缩文件到指定大小,我期望的是150KB,step和quality可以修改到最合适的数值六:
项目中大量用到图片加载,由于图片太大,加载速度很慢,因此需要对文件进行统一压缩
python -m pip install Pillow
from PIL import Image
import os
def get_size(file):
# 获取文件大小:KB
size = os.path.getsize(file)
return size / 1024
dir_path = r'file_path'
items = os.listdir(dir_path)
for item in items:
# print(item)
path = os.path.join(dir_path, item)
print(item)
def compress_image(infile, outfile=None, mb=150, step=10, quality=80):
"""不改变图片尺寸压缩到指定大小
:param infile: 压缩源文件
:param outfile: 压缩文件保存地址
:param mb: 压缩目标,KB
:param step: 每次调整的压缩比率
:param quality: 初始压缩比率
:return: 压缩文件地址,压缩文件大小
"""
if outfile is None:
outfile = infile
o_size = get_size(infile)
if o_size <= mb:
im = Image.open(infile)
im.save(outfile)
while o_size > mb:
im = Image.open(infile)
im.save(outfile, quality=quality)
if quality - step < 0:
break
quality -= step
o_size = get_size(outfile)
def resize_image(infile, outfile='', x_s=800):
"""修改图片尺寸
:param infile: 图片源文件
:param outfile: 重设尺寸文件保存地址
:param x_s: 设置的宽度
:return:
"""
im = Image.open(infile)
x, y = im.size
y_s = int(y * x_s / x)
out = im.resize((x_s, y_s), Image.ANTIALIAS)
out.save(outfile)
if __name__ == '__main__':
# 源路径 # 压缩后路径
compress_image(r"file_path", r"E:\docs\2.JPG")
# 源路径 # 压缩后路径
resize_image(r"file_path", r"E:\docs\3.JPG")
import os
from PIL import Image
import threading,time
def imgToProgressive(path):
if not path.split('.')[-1:][0] in ['png','jpg','jpeg']: #if path isn't a image file,return
return
if os.path.isdir(path):
return
##########transfORM img to progressive
img = Image.open(path)
destination = path.split('.')[:-1][0]+'_destination.'+path.split('.')[-1:][0]
try:
print(path.split('\\')[-1:][0],'开始转换图片')
img.save(destination, "JPEG", quality=80, optimize=True, progressive=True) #转换就是直接另存为
print(path.split('\\')[-1:][0],'转换完毕')
except IOError:
PIL.ImageFile.MAXBLOCK = img.size[0] * img.size[1]
img.save(destination, "JPEG", quality=80, optimize=True, progressive=True)
print(path.split('\\')[-1:][0],'转换完毕')
print('开始重命名文件')
os.remove(path)
os.rename(destination,path)
for d,_,fl in os.walk(os.getcwd()): #遍历目录下所有文件
for f in fl:
try:
imgToProgressive(d+'\\'+f)
except:
pass
--结束END--
本文标题: python实现图片批量压缩
本文链接: https://lsjlt.com/news/124432.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0