An Example of Image Batch Compression by python

  • 2021-08-28 20:34:17
  • OfStack

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

1: Import package


from PIL import Image
import os

2: Get the size of the picture file


def get_size(file):
  #  Get the file size :KB
  size = os.path.getsize(file)
  return size / 1024

3: Splice output file address


def get_outfile(infile, outfile):
  if outfile:
    return outfile
  dir, suffix = os.path.splitext(infile)
  outfile = '{}-out{}'.format(dir, suffix)
  return outfile

4: Compress the file to the specified size. I expect that 150KB, step and quality can be modified to the most appropriate values


def compress_image(infile, outfile='', 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 
  """
  o_size = get_size(infile)
  if o_size <= mb:
    return infile
  outfile = get_outfile(infile, 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)
  return outfile, get_size(outfile)

5: 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


#Python Learning and communication group: 778463939
def resize_image(infile, outfile='', x_s=1376):
  """ 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)
  outfile = get_outfile(infile, outfile)
  out.save(outfile)


if __name__ == '__main__':
  compress_image(r'D:\learn\space.jpg')
  resize_image(r'D:\learn\space.jpg')

The above is the python image batch compression example details, more about python image batch compression information please pay attention to this site other related articles!


Related articles: