项目中大量用到图片加载,由于图片太大,加载速度很慢,因此需要对文件进行统一压缩
第一种
一:安装包
1
|
python - m pip install Pillow |
二:导入包
1
2
|
from PIL import Image import os |
三:获取图片文件的大小
1
2
3
4
|
def get_size( file ): # 获取文件大小:KB size = os.path.getsize( file ) return size / 1024 |
四:输出文件夹下的文件
1
2
3
4
5
6
7
|
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可以修改到最合适的数值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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) |
六:修改图片尺寸,如果同时有修改尺寸和大小的需要,可以先修改尺寸,再压缩大小
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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) |
七:运行程序
1
2
3
4
5
|
if __name__ = = '__main__' : # 源路径 # 压缩后路径 compress_image(r "file_path" , r "E:\docs\2.JPG" ) # 源路径 # 压缩后路径 resize_image(r "file_path" , r "E:\docs\3.JPG" ) |
第二种
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
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 |
以上就是python实现图片批量压缩的详细内容,更多关于python 图片压缩的资料请关注服务器之家其它相关文章!
原文链接:https://www.cnblogs.com/shizhengwen/p/14638246.html