Last active
December 8, 2024 11:52
-
-
Save sdvcrx/097bc635206ff0157599598bf60bef84 to your computer and use it in GitHub Desktop.
Compressing images using libvips
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
import pyvips | |
options = { | |
'Q': 75, | |
'quant_table': 3, | |
'interlace': True, | |
'strip': True, | |
'optimize_coding': True, | |
'optimize_scans': True, | |
'trellis_quant': True, | |
} | |
def transform(filename: str): | |
image = pyvips.Image.new_from_file(filename, access='sequential') | |
print('Compressing {} ...'.format(filename)) | |
dir = os.path.join(os.path.dirname(filename), 'dist') | |
name, ext = os.path.splitext(os.path.basename(filename)) | |
output_filename = os.path.join(dir, '{}.{}'.format(name, 'jpg')) | |
if ext == '.png': | |
image.autorot().write_to_file(output_filename, **options) | |
else: | |
image.autorot().resize(0.5).write_to_file(output_filename, **options) | |
def is_image(f: str) -> bool: | |
return f.endswith('jpg') or f.endswith('JPG') or f.endswith('png') | |
def transform_dir(dir: str): | |
output_dir = os.path.join(dir, 'dist') | |
os.makedirs(output_dir, exist_ok=True) | |
images = [os.path.join(dir, f) for f in os.listdir(dir) if is_image(f)] | |
for f in images: | |
transform(f) | |
# Usage: python compress_img.py /path/to/dir | |
if __name__ == "__main__": | |
dirs = [d for d in sys.argv[1:] if os.path.isdir(d)] | |
for d in dirs: | |
transform_dir(d) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment