Realization of Image Batch Compression with python
- 2021-11-01 04:11:17
- OfStack
Directory 1 1: Installation Package 2: Import Package 3: Get the size of the picture file 4: Output folder 5: Compress the file to the specified size, I expect 150KB, step and quality can be modified to the most appropriate value 6: Modify the picture size, if there is a need to modify the size and size at the same time, you can modify the size first, and then compress the size 7: Run the program 2
A large number of pictures are used in the project to load. Because the pictures are too large and the loading speed is slow, it is necessary to compress the files in a unified way
Type 1
1: Installation package
python -m pip install Pillow
2: Import package
from PIL import Image
import os
3: Get the size of the picture file
def get_size(file):
# Get the file size :KB
size = os.path.getsize(file)
return size / 1024
4: Files under the output folder
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)
5: Compress the file to the specified size. I expect 150KB, step and quality to be modified to the most appropriate values
def compress_image(infile, outfile=None, mb=150, step=10, quality=80):
""" Compress the picture to the specified size without changing the size
:param infile: Compress source file
:param outfile: Save address of compressed file
:param mb: Compress the target, KB
:param step: Compression ratio per adjustment
:param quality: Initial compression ratio
:return: Compressed file address, compressed file size
"""
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)
6: Modify the size of the picture. If you need to modify the size and size at the same time, you can modify the size first and then compress the size
def resize_image(infile, outfile='', x_s=800):
""" Modify picture size
:param infile: Picture source file
:param outfile: Reset Size File Save Address
:param x_s: Set width
: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)
7: Run the program
if __name__ == '__main__':
# Source path # Path after compression
compress_image(r"file_path", r"E:\docs\2.JPG")
# Source path # Path after compression
resize_image(r"file_path", r"E:\docs\3.JPG")
Type 2
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],' Start converting pictures ')
img.save(destination, "JPEG", quality=80, optimize=True, progressive=True) # Conversion is to save directly as
print(path.split('\\')[-1:][0],' Conversion complete ')
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],' Conversion complete ')
print(' Start renaming files ')
os.remove(path)
os.rename(destination,path)
for d,_,fl in os.walk(os.getcwd()): # Traverse all files in the directory
for f in fl:
try:
imgToProgressive(d+'\\'+f)
except:
pass
The above is the python image batch compression details, more information about python image compression please pay attention to other related articles on this site!