Use lossless webp, fix jpg generation

This commit is contained in:
rubenwardy 2023-11-12 16:11:38 +00:00
parent c546eef6a9
commit b4c508ebab

@ -36,21 +36,20 @@ def mkdir(path):
def resize_and_crop(img_path, modified_path, size): def resize_and_crop(img_path, modified_path, size):
img = Image.open(img_path) with Image.open(img_path) as img:
# Get current and desired ratio for the images # Get current and desired ratio for the images
img_ratio = img.size[0] / float(img.size[1]) img_ratio = img.size[0] / float(img.size[1])
ratio = size[0] / float(size[1]) desired_ratio = size[0] / float(size[1])
# Is more portrait than target, scale and crop # Is more portrait than target, scale and crop
if ratio > img_ratio: if desired_ratio > img_ratio:
img = img.resize((int(size[0]), int(size[0] * img.size[1] / img.size[0])), img = img.resize((int(size[0]), int(size[0] * img.size[1] / img.size[0])),
Image.BICUBIC) Image.BICUBIC)
box = (0, (img.size[1] - size[1]) / 2, img.size[0], (img.size[1] + size[1]) / 2) box = (0, (img.size[1] - size[1]) / 2, img.size[0], (img.size[1] + size[1]) / 2)
img = img.crop(box) img = img.crop(box)
# Is more landscape than target, scale and crop # Is more landscape than target, scale and crop
elif ratio < img_ratio: elif desired_ratio < img_ratio:
img = img.resize((int(size[1] * img.size[0] / img.size[1]), int(size[1])), img = img.resize((int(size[1] * img.size[0] / img.size[1]), int(size[1])),
Image.BICUBIC) Image.BICUBIC)
box = ((img.size[0] - size[0]) / 2, 0, (img.size[0] + size[0]) / 2, img.size[1]) box = ((img.size[0] - size[0]) / 2, 0, (img.size[0] + size[0]) / 2, img.size[1])
@ -60,7 +59,10 @@ def resize_and_crop(img_path, modified_path, size):
else: else:
img = img.resize(size, Image.BICUBIC) img = img.resize(size, Image.BICUBIC)
img.save(modified_path) if modified_path.endswith(".jpg") and img.mode != "RGB":
img = img.convert("RGB")
img.save(modified_path, lossless=True)
def find_source_file(img): def find_source_file(img):