Edit: This question has been marked a duplicate? My question is clearly about optimising this process, not HOW to do it. I even provided code to prove that I had already figured out the latter. Do you internet hall monitors even read these questions past the title before you flag them?
I have the following block of code to compress an image using PIL, until said image is under a certain size.
from PIL import Image
import os
def compress(image_file, max_size, scale):
while os.path.getsize(image_file) > max_size:
pic = Image.open(image_file)
original_size = pic.size
pic = pic.resize((int(original_size[0] * scale),
int(original_size[1] * scale)),
Image.ANTIALIAS)
pic.save(image_file, optimize=True, quality=95)
In this code, I use os.path.getsize(image_file)
to get the size of the image. However, this means that the file must be saved in pic.save(image_file, optimize=True, quality=95
every time the loop runs.
That process takes a long time.
Is there a way to optimise this by somehow getting the size of the image in the PIL
Image
object pic
?