36 lines
1.2 KiB
Python
36 lines
1.2 KiB
Python
#!/usr/bin/env python3
|
|
import json
|
|
import os
|
|
import sys
|
|
from PIL import Image
|
|
|
|
source, target, cap, quality = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4])
|
|
ext = os.path.splitext(target)[1].lower()
|
|
with Image.open(source) as image:
|
|
image = image.convert('RGB')
|
|
source_width, source_height = image.size
|
|
if len(sys.argv) == 9:
|
|
x, y, width, height = [int(v) for v in sys.argv[5:9]]
|
|
image = image.crop((x, y, x + width, y + height))
|
|
scale = min(1.0, cap / max(image.width, image.height))
|
|
if scale < 1.0:
|
|
image = image.resize((round(image.width * scale), round(image.height * scale)), Image.Resampling.LANCZOS)
|
|
if ext in ('.jpg', '.jpeg'):
|
|
image.save(target, 'JPEG', quality=quality, optimize=True)
|
|
mime = 'image/jpeg'
|
|
elif ext == '.png':
|
|
image.save(target, 'PNG', optimize=True)
|
|
mime = 'image/png'
|
|
else:
|
|
image.save(target, 'WEBP', quality=quality, method=4)
|
|
mime = 'image/webp'
|
|
|
|
print(json.dumps({
|
|
'source_width': source_width,
|
|
'source_height': source_height,
|
|
'width': image.width,
|
|
'height': image.height,
|
|
'scale': scale,
|
|
'mime': mime,
|
|
}))
|