def rescale_image(data, maxsizeb=IMAGE_MAX_SIZE, dimen=None): ''' Convert image setting all transparent pixels to white and changing format to JPEG. Ensure the resultant image has a byte size less than maxsizeb. If dimen is not None, generate a thumbnail of width=dimen, height=dimen or width, height = dimen (depending on the type of dimen) Returns the image as a bytestring ''' if dimen is not None: if hasattr(dimen, '__len__'): width, height = dimen else: width = height = dimen data = thumbnail(data, width=width, height=height, compression_quality=90)[-1] else: # Replace transparent pixels with white pixels and convert to JPEG data = save_cover_data_to(data, 'img.jpg', return_data=True) if len(data) <= maxsizeb: return data orig_data = data img = Image() quality = 95 img.load(data) while len(data) >= maxsizeb and quality >= 10: quality -= 5 img.set_compression_quality(quality) data = img.export('jpg') if len(data) <= maxsizeb: return data orig_data = data scale = 0.9 while len(data) >= maxsizeb and scale >= 0.05: img = Image() img.load(orig_data) w, h = img.size img.size = (int(scale * w), int(scale * h)) img.set_compression_quality(quality) data = img.export('jpg') scale -= 0.05 return data
def rescale_image(data, maxsizeb=IMAGE_MAX_SIZE, dimen=None): ''' Convert image setting all transparent pixels to white and changing format to JPEG. Ensure the resultant image has a byte size less than maxsizeb. If dimen is not None, generate a thumbnail of width=dimen, height=dimen or width, height = dimen (depending on the type of dimen) Returns the image as a bytestring ''' if dimen is not None: if hasattr(dimen, '__len__'): width, height = dimen else: width = height = dimen data = thumbnail(data, width=width, height=height, compression_quality=90)[-1] else: # Replace transparent pixels with white pixels and convert to JPEG data = save_cover_data_to(data, 'img.jpg', return_data=True) if len(data) <= maxsizeb: return data orig_data = data img = Image() quality = 95 img.load(data) while len(data) >= maxsizeb and quality >= 10: quality -= 5 img.set_compression_quality(quality) data = img.export('jpg') if len(data) <= maxsizeb: return data orig_data = data scale = 0.9 while len(data) >= maxsizeb and scale >= 0.05: img = Image() img.load(orig_data) w, h = img.size img.size = (int(scale*w), int(scale*h)) img.set_compression_quality(quality) data = img.export('jpg') scale -= 0.05 return data