from pathlib import Path from PIL import Image from base_proxy import BASE_DIR from sheet_layout import SheetLayout, CardImageTransfer W_INCHES_EXPECTED = 2.72 H_INCHES_EXPECTED = 3.7 SAVE_INTERMEDIATE_FOR_DEBUG = False def make_intermediate_name(input_path: Path, infix: str): return BASE_DIR / 'cropped_cards' / f'{input_path.stem}.{infix}.jpg' class InputCardImage: def __init__(self, path: Path): self.path = path self.input_dpi = None self.original_im = None def load(self) -> None: with Image.open(self.path) as im: # print(im.info) rgb_im = im.convert('RGB') w, h = rgb_im.width, rgb_im.height dpi_by_w = w / W_INCHES_EXPECTED dpi_by_h = h / H_INCHES_EXPECTED print(f'Image is {w} x {h}, {dpi_by_w} dpi (by width)') if dpi_by_h != dpi_by_w: print(f'By height dpi is different: {dpi_by_h} dpi') self.input_dpi = dpi_by_w self.original_im = rgb_im def get_cropped_and_resized(self, layout: SheetLayout, transfer: CardImageTransfer) -> Image: new_dpi = layout.dpi self.load() im = self.original_im print(f'Input is {im.size[0]} x {im.size[1]}') # Resize to match sheet DPI new_w = layout.in_to_px(W_INCHES_EXPECTED) new_h = layout.in_to_px(H_INCHES_EXPECTED) print(f'Resized input to {new_w} x {new_h}') im = im.resize((new_w, new_h), resample=Image.Resampling.LANCZOS) if SAVE_INTERMEDIATE_FOR_DEBUG: im.save(make_intermediate_name(self.path, 'step1resize'), 'JPEG', dpi=(layout.dpi, layout.dpi), quality=100, subsampling=0) # Crop left = (new_w - layout.card_w) // 2 right = left + layout.card_w top = (new_h - layout.card_h) // 2 bottom = top + layout.card_h if transfer.bleeds[0]: top -= layout.leave_bleed if transfer.bleeds[1]: bottom += layout.leave_bleed if transfer.bleeds[2]: left -= layout.leave_bleed if transfer.bleeds[3]: right += layout.leave_bleed # Crop crop_box = (left, top, right, bottom) print(f'Cropped box {crop_box}') im = im.crop(crop_box) if SAVE_INTERMEDIATE_FOR_DEBUG: im.save(make_intermediate_name(self.path, 'step2crop'), 'JPEG', dpi=(layout.dpi, layout.dpi), quality=100, subsampling=0) return im