I'm attempting to write a program that will take an image file I input, save a new compressed version at 50% its original quality, then open the new file and run again n number of times. Essentially I need it to be a huge compression feedback loop that creates a new file each time. It's for a visual art project.
Unfortunately it doesn't look like PIL will recompress files that were created using its own compression algorithm, so basically when I try to run it I end up with n number of the same exact file.
I'm using PIL and Python 3.3 on an Intel Mac running OS X 10.7. This is the entire program:
import os
from PIL import Image
def compressLoop(infile, times):
'''
Progressively loads, compresses, creates files based on original JPEG 'times' number of times.
'''
n = 1
baseName, e = os.path.splitext(infile)
try:
while n <= times:
f, e = os.path.splitext(infile)
f = (baseName + str(n))
outfile = f + ".jpg"
#open previously generated file
compImg = Image.open(infile)
#compress file at 50% of previous quality
compImg.save(outfile, "JPEG", quality=50)
infile = outfile
n = n+1
except IOError:
print("Cannot convert", infile)
def main():
infile = str(input("Filename to compress: "))
times = int(input("Times to process: "))
compressLoop(infile, times)
main()
Are there any workarounds to this problem? Am I using the right function in compImg.save(outfile, "JPEG", quality=50) or is there another way to compress image files?
Thanks in advance for the help!