"""This module contains image validation methods.""" import numpy as np from constants import errors from constants import image_standards def validate_dimensions(*, width, height): """Check image dimensions for cover images. Args: width (int): Image width. height (int): Image height. Returns: str: The result of image dimensions validation. Error code in case of an error """ if width != height: return errors.IMAGE_WRONG_ASPECT_RATIO_CODE if width < image_standards.MIN_IMAGE_DIMENSION: return errors.IMAGE_TOO_SMALL_DIMENSIONS_CODE if width > image_standards.MAX_IMAGE_DIMENSION: return errors.IMAGE_TOO_LARGE_DIMENSIONS_CODE return image_standards.VALID_DIMENSIONS_CODE def validate_mode(mode): """Check image mode. https://pillow.readthedocs.io/en/5.2.x/handbook/concepts.html#concept-modes Args: mode (str): image mode value Returns: bool: True if mode is valid, False otherwise """ return mode in image_standards.VALID_MODES def validate_is_opaque(image): """Check if an image is fully opaque. Args: image (PIL.Image.Image): Image to check. Returns: bool: True if image is fully opaque, False otherwise. """ if image.mode in image_standards.VALID_MODES_WITHOUT_ALPHA_CHANNEL: return True if image.mode in image_standards.VALID_MODES_WITH_ALPHA_CHANNEL - {'RGBA'}: image = image.convert('RGBA') np_img = np.array(image) return np.all(np_img[:, :, 3] == 255)