Skip to content

Instantly share code, notes, and snippets.

@Zebartin
Created July 29, 2023 13:18
Show Gist options
  • Save Zebartin/0799d80744d3a373237f178950c620c7 to your computer and use it in GitHub Desktop.
Save Zebartin/0799d80744d3a373237f178950c620c7 to your computer and use it in GitHub Desktop.
Python: resize image to specified file size
from io import BytesIO
from pathlib import Path
from PIL import Image
def resize_image(image_path: Path, max_size: int=3*1024*1024):
if image_path.stat().st_size <= max_size:
return image_path.read_bytes()
img = Image.open(image_path)
if img.format != 'PNG':
with BytesIO() as tmp_io:
img.save(tmp_io, format=img.format, quality=90, optimize=True)
if tmp_io.tell() <= max_size:
return tmp_io.getvalue()
new_img_value = None
width, height = img.size
l = 100
r = int(height / 10) + 1
# print(f'original size: {width, height}')
# print(f'file size: {image_path.stat().st_size/1024/1024:.2f}MB')
while l < r:
m = int((l + r) / 2)
new_height = m*10
new_width = round(new_height / height * width)
new_img = img.resize((new_width, new_height), Image.LANCZOS)
with BytesIO() as tmp_io:
new_img.save(tmp_io, format=img.format, quality=90, optimize=True)
new_file_size = tmp_io.tell()
new_img_value = tmp_io.getvalue()
# print(f'new size: {new_width, new_height}')
# print(f'file size: {new_file_size/1024/1024:.2f}MB')
if abs(new_file_size - max_size) < 0.2*1024*1024:
break
if new_file_size < max_size:
l = m + 1
else:
r = m
return new_img_value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment