您的位置:首页技术文章
文章详情页

python实现图片批量压缩

【字号: 日期:2022-06-21 14:08:42浏览:3作者:猪猪

项目中大量用到图片加载,由于图片太大,加载速度很慢,因此需要对文件进行统一压缩

第一种 一:安装包

python -m pip install Pillow二:导入包

from PIL import Imageimport 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)五:压缩文件到指定大小,我期望的是150KB,step和quality可以修改到最合适的数值

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: breakquality -= stepo_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:docs2.JPG') # 源路径 # 压缩后路径 resize_image(r'file_path', r'E:docs3.JPG')第二种

import osfrom PIL import Imageimport threading,timedef imgToProgressive(path): if not path.split(’.’)[-1:][0] in [’png’,’jpg’,’jpeg’]: #if path isn’t a image file,returnreturn 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

以上就是python实现图片批量压缩的详细内容,更多关于python 图片压缩的资料请关注好吧啦网其它相关文章!

标签: Python 编程
相关文章: