Skip to content

Instantly share code, notes, and snippets.

@DeusFigendi
Created May 4, 2019 15:10
Show Gist options
  • Save DeusFigendi/961026ab317ab80eb125a8db2217478f to your computer and use it in GitHub Desktop.
Save DeusFigendi/961026ab317ab80eb125a8db2217478f to your computer and use it in GitHub Desktop.
Reduces size of all files in the working directory
from __future__ import print_function
import os, sys
import shutil
from PIL import Image
file_list = os.listdir("./")
target_size = 4000*1024
start_quality = 95
current_quality = 95
try:
os.mkdir('./small')
except OSError:
pass
for infile in file_list:
print("processing "+infile+' ('+str(os.path.getsize(infile))+')')
if (os.path.getsize(infile) < target_size):
try:
shutil.copy('./'+infile,'./small/'+infile)
except IsADirectoryError:
pass
else:
outfile = './small/'+infile
if infile != outfile:
try:
original_image = Image.open(infile)
new_size = original_image.size
original_image.save(outfile,"JPEG",quality=int(current_quality))
while (os.path.getsize(outfile) > target_size):
print("+--processing "+infile+' ('+str(os.path.getsize(outfile))+')')
current_quality = current_quality * 0.98
new_size = (new_size[0] * 0.98,new_size[1] * 0.98)
new_size_int = (int(new_size[0]),int(new_size[1]))
new_image = original_image.resize(new_size_int)
new_image.save(outfile,"JPEG",quality=int(current_quality))
current_quality = 95
except IOError:
print("cannot convert", infile)
print("+-----reduced "+infile+' to '+str(os.path.getsize(outfile)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment