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,31 +36,33 @@ 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
img_ratio = img.size[0] / float(img.size[1])
desired_ratio = size[0] / float(size[1])
# Get current and desired ratio for the images # Is more portrait than target, scale and crop
img_ratio = img.size[0] / float(img.size[1]) if desired_ratio > img_ratio:
ratio = size[0] / float(size[1]) img = img.resize((int(size[0]), int(size[0] * img.size[1] / img.size[0])),
Image.BICUBIC)
box = (0, (img.size[1] - size[1]) / 2, img.size[0], (img.size[1] + size[1]) / 2)
img = img.crop(box)
# Is more portrait than target, scale and crop # Is more landscape than target, scale and crop
if ratio > img_ratio: elif desired_ratio < img_ratio:
img = img.resize((int(size[0]), int(size[0] * img.size[1] / img.size[0])), img = img.resize((int(size[1] * img.size[0] / img.size[1]), int(size[1])),
Image.BICUBIC) Image.BICUBIC)
box = (0, (img.size[1] - size[1]) / 2, img.size[0], (img.size[1] + size[1]) / 2) box = ((img.size[0] - size[0]) / 2, 0, (img.size[0] + size[0]) / 2, img.size[1])
img = img.crop(box) img = img.crop(box)
# Is more landscape than target, scale and crop # Is exactly the same ratio as target
elif ratio < img_ratio: else:
img = img.resize((int(size[1] * img.size[0] / img.size[1]), int(size[1])), img = img.resize(size, Image.BICUBIC)
Image.BICUBIC)
box = ((img.size[0] - size[0]) / 2, 0, (img.size[0] + size[0]) / 2, img.size[1])
img = img.crop(box)
# Is exactly the same ratio as target if modified_path.endswith(".jpg") and img.mode != "RGB":
else: img = img.convert("RGB")
img = img.resize(size, Image.BICUBIC)
img.save(modified_path) img.save(modified_path, lossless=True)
def find_source_file(img): def find_source_file(img):