from pathlib import Path from PIL import Image from base_proxy import LEAVE_BLEED_INCHES from sheet_layout import SheetLayout W_INCHES_EXPECTED = 2.72 H_INCHES_EXPECTED = 3.7 BLEED_INCHES_EXPECTED = 0.12 class InputCardImage: def __init__(self, path: Path): self.path = path def crop(self) -> Image: 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'By width dpi is {dpi_by_w} dpi') if dpi_by_h != dpi_by_w: print(f'dpi by height is different: {dpi_by_h} dpi') crop_pixels = BLEED_INCHES_EXPECTED * dpi_by_w - LEAVE_BLEED_INCHES * dpi_by_w crop_pixels_int = round(crop_pixels) print(f'Image is {w} x {h}, will trim {crop_pixels} pixels (rounded to {crop_pixels_int})') # Crop crop_box = (crop_pixels_int, crop_pixels_int, w - crop_pixels_int, h - crop_pixels_int) cropped_part = rgb_im.crop(crop_box) return cropped_part def get_cropped_and_resized(self, sheet_layout: SheetLayout) -> Image: im = self.crop() im = im.resize((sheet_layout.cropped_image_dest_w, sheet_layout.cropped_image_dest_h), resample=Image.Resampling.LANCZOS) return im