"""Image loading and normalisation helpers.""" import io import cv2 import numpy as np from PIL import Image, ImageOps from config.runtime import ROOM_UPLOAD_JPEG_QUALITY, ROOM_UPLOAD_MAX_DIMENSION from errors import bad_request def load_tile_image(contents: bytes) -> np.ndarray: try: return np.array(Image.open(io.BytesIO(contents)).convert("RGB")) except Exception as exc: bad_request("Upload must be a readable tile image.", exc) def load_uploaded_rgb_image(contents: bytes) -> tuple[Image.Image, np.ndarray]: try: image = Image.open(io.BytesIO(contents)).convert("RGB") except Exception as exc: bad_request("Upload must be a readable image.", exc) return image, np.array(image) def normalize_room_upload(contents: bytes) -> bytes: try: image = Image.open(io.BytesIO(contents)) image.load() except Exception as exc: bad_request("Upload must be a readable image.", exc) source_format = (image.format or "").upper() has_alpha = image.mode in {"RGBA", "LA"} or (image.mode == "P" and "transparency" in image.info) width, height = image.size largest = max(width, height) needs_resize = largest > ROOM_UPLOAD_MAX_DIMENSION try: orientation = image.getexif().get(274) except Exception: orientation = None needs_orientation = orientation not in {None, 1} if source_format == "JPEG" and not has_alpha and not needs_resize and not needs_orientation: return contents image = ImageOps.exif_transpose(image) if has_alpha: alpha = image.convert("RGBA") background = Image.new("RGB", alpha.size, (255, 255, 255)) background.paste(alpha, mask=alpha.getchannel("A")) image = background else: image = image.convert("RGB") width, height = image.size largest = max(width, height) if largest > ROOM_UPLOAD_MAX_DIMENSION: scale = ROOM_UPLOAD_MAX_DIMENSION / float(largest) target_size = ( max(1, int(round(width * scale))), max(1, int(round(height * scale))), ) image = image.resize(target_size, Image.Resampling.LANCZOS) buffer = io.BytesIO() image.save(buffer, format="JPEG", quality=ROOM_UPLOAD_JPEG_QUALITY, optimize=True) return buffer.getvalue()