Compress + Resize Bulk Images in python


from PIL import Image
import shutil
import os, sys

basewidth = 1600

def compress(filename, destfilename, quality_num, cropsize = (), whitebg = False):
  # Make PNG Background White
  if whitebg:
    fill_color = (255,255,255)
    im = Image.open(filename)
    im = im.convert('RGBA')
    background = Image.new(im.mode[:-1], im.size, fill_color)
    background.paste(im, im.split()[-1]) # omit transparency
    original = background
  else:
    original = Image.open(filename)

  # Check PNG Images with no Trasperant Data
  if filename.endswith(".png"):
    original = original.convert('RGBA')
    datas = original.getdata()
    flagTrasperant = False
    for item in datas:
      if(len(item) < 4): flagTrasperant = False break elif item[3] == 0: flagTrasperant = True break if not flagTrasperant: # If given image does not contain transperant pixels -> convert it into JPG
      destfilename = destfilename.replace(".png", ".jpg")
      original = original.convert('RGB')

  # Resize Logic
  width, height = original.size
  if width > 1600 or height > 1600:
    width2, height2 = getResizeSize(width, height)
    original = original.resize((width2, height2), Image.ANTIALIAS)
    original.save(destfilename, quality = quality_num)
  else:
    original.save(destfilename, quality = quality_num)

  # Crop Logic
  if(len(cropsize) > 0):
    # left, top, right, bottom
    original = Image.open(destfilename)
    original = original.crop(cropsize)
    original.save(destfilename, quality = quality_num)

  return destfilename

def getResizeSize(width, height):
  if ( width - height ) > 50:
    # Horizontal
    wpercent = (basewidth / float(width))
    hsize = int((float(height) * float(wpercent)))
    return basewidth, hsize
  elif ( height - width ) > 50:
    # Vertical
    wpercent = (basewidth / float(height))
    wsize = int((float(width) * float(wpercent)))
    return wsize, basewidth
  else:
    # Comparitively Square
    wpercent = (basewidth / float(width))
    hsize = int((float(height) * float(wpercent)))
    return basewidth, hsize

print "----------------------------------- Start -----------------------------------"

print "folder", "\t", "width", "x", "height", "\t ", "width new", "x", "height new", "\t", "size old", "\t", "size new", "\t", "Size Diff", "\t", "filename", "\t", "destfilename", "\t", "Is Converted"

count = 0
count_dim = 0
count_highsize = 0
count_versions = 0
folders = ["Multiple", "Input", "Folders"]

for folder in folders:
  for filename in os.listdir(folder):
    
    if os.path.exists("Converted/" + folder + "/" + filename):
      continue

    if filename.endswith(".png") or filename.endswith(".jpg"):
      if "x" not in filename:
        # print folder + "/" + filename
        im = Image.open(folder + "/" + filename)
        width, height = im.size
        size = os.stat(folder + "/" + filename).st_size / 1000
        if width > 1600 or height > 1600:
          width2, height2 = getResizeSize(width, height)
          destfilename = compress(folder + "/"+filename, "Converted/"+folder+"/"+filename, 90) 
          size_new = os.stat(destfilename).st_size / 1000
          if size_new > size:
            os.remove(destfilename)
            continue
          converted = ""
          if filename not in destfilename:
            converted = "TRUE"

          destfilename_short = destfilename.replace("Converted/"+folder+"/", "")

          print folder, "\t", width, "x", height, "\t ", width2, "x", height2, "\t", size, "\t", size_new, "\t", str(size - size_new), "\t", filename, "\t", destfilename_short, "\t", converted
          count = count + 1
          count_dim = count_dim + 1
        else:
          if size > 500:
            print folder, "\t", width, "x", height, "\t\t", size, "\t", filename
            count = count + 1
            count_highsize = count_highsize + 1
      else:
        count_versions = count_versions + 1

print "Total count: ", count
print "Total count_dim: ", count_dim
print "Total count_highsize: ", count_highsize
print "Total count_versions: ", count_versions

print "----------------------------------- Done -----------------------------------"

Download source file from dwij.net/p/resize_compress.py.

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.