From a316da89b9c2d1bca66bbb64572f9ba9e03f2f95 Mon Sep 17 00:00:00 2001 From: hkc Date: Tue, 17 Oct 2023 14:40:09 +0300 Subject: [PATCH] thumbnail -> fill rectangle --- cc-pic.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/cc-pic.py b/cc-pic.py index e31f227..83dd74f 100644 --- a/cc-pic.py +++ b/cc-pic.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# x-run: python3 % ~/downloads/kanade/6bf3cdae12b75326e3c23af73105e5781e42e94e.jpg +# x-run: python3 % ~/downloads/kanade/6bf3cdae12b75326e3c23af73105e5781e42e94e.jpg n25.cpi from typing import BinaryIO, TextIO from PIL import Image @@ -33,10 +33,8 @@ class Converter: MAX_DIFF = (3 ** 0.5) * 255 - def __init__(self, image: Image.Image, size: tuple[int, int]): - self._img = image.copy() - self._img.thumbnail(( size[0] * 2, size[1] * 3 )) - self._img = self._img.convert("P", palette=Image.ADAPTIVE, colors=16) + def __init__(self, image: Image.Image): + self._img = image.convert("P", palette=Image.ADAPTIVE, colors=16) self._palette: list[int] = self._img.getpalette() # type: ignore def _brightness(self, i: int) -> float: @@ -119,9 +117,14 @@ class Converter: def main(fp_in, fp_out): - with Image.open(fp_in) as img: - with open(fp_out, "wb") as fp: - Converter(img, (164, 81)).export_binary(fp) + size = 143 * 2, 81 * 3 # 286, 243 + with Image.new("RGB", size) as canv: + with Image.open(fp_in) as img: + scale = max(img.width / size[0], img.height / size[0]) + img = img.resize((int(img.width / scale), int(img.height / scale))) + canv.paste(img, ((canv.width - img.width) // 2, (canv.height - img.height) // 2)) + with open(fp_out, "wb") as fp: + Converter(canv).export_binary(fp) if __name__ == "__main__": main(argv[1], argv[2])