comfycamp/convert-images.py

77 lines
2 KiB
Python

import subprocess
from os import listdir, path, makedirs
from os.path import isfile, join, splitext, exists
def main():
convert_favicon()
convert_images('public-src', 'public')
def convert_favicon():
"""
Generate different versions of an icon from a vector image.
The function does not overwrite existing files.
"""
root = 'public/favicon'
src = f'{root}/vector.svg'
sizes = [512, 192, 180, 32, 16]
for size in sizes:
dest = f'{root}/{size}.png'
if exists(dest):
continue
cmd = ['convert', src, '-resize', f'{size}x{size}', f'{root}/{size}.png']
print(' '.join(cmd))
subprocess.run(cmd)
dest = f'{root}/shortcut.ico'
if exists(dest):
return
cmd = [
'convert', src,
'(', '-clone', '0', '-resize', '16x16', ')',
'(', '-clone', '0', '-resize', '32x32', ')',
'(', '-clone', '0', '-resize', '48x48', ')',
'-delete', '0', '-alpha', 'remove', '-colors', '256',
f'{root}/shortcut.ico',
]
print(' '.join(cmd))
subprocess.run(cmd)
def convert_images(src, dest):
"""
Convert all images from the public-src directory.
The function does not overwrite existing files.
Example:
public-src/subdir/1.jpg -> public/subdir/1.avif
"""
for i in listdir(src):
entry = join(src, i)
if isfile(entry):
if splitext(i.lower())[1] not in ['.png', '.jpg', '.jpeg']:
continue
dest_file = join(dest, i)
dest_file = splitext(dest_file)[0] + '.avif'
if exists(dest_file):
continue
cmd = ['convert', entry, '-resize', '1200x', '-quality', '80', dest_file]
print(' '.join(cmd))
subprocess.run(cmd)
else:
target_dir = join(dest, i)
makedirs(target_dir, exist_ok=True)
convert_images(entry, target_dir)
if __name__ == '__main__':
main()