|
| 1 | +from pathlib import Path |
| 2 | +from threading import Thread |
| 3 | +from typing import Tuple, Union |
| 4 | +from uuid import uuid4 |
| 5 | + |
| 6 | +from PIL import Image |
| 7 | + |
| 8 | +from image_utils.config import settings |
| 9 | +from image_utils.image_resizer.base import IImageResizer |
| 10 | +from image_utils.core.utils import print_if_verbose |
| 11 | +from image_utils.validators.base import IValidator |
| 12 | + |
| 13 | + |
| 14 | +class ImageResizer(IImageResizer): |
| 15 | + def __init__(self, validator: IValidator) -> None: |
| 16 | + self.validator = validator() |
| 17 | + |
| 18 | + def resize_image(self, img_path: Union[Path, str], |
| 19 | + *, extension: str = None, |
| 20 | + img_height: int = 200, img_width: int = 200) -> Path: |
| 21 | + """ |
| 22 | + Resizes an image file to the new height and width as well as |
| 23 | + a new extension type if extension is provided |
| 24 | +
|
| 25 | + * `args`: |
| 26 | + `img_path`:`Path` | `str` -> Path to the image file to be processed |
| 27 | +
|
| 28 | + * `kwargs`: |
| 29 | + `extension`:`str` -> Defaults to `None`, If it is provided the |
| 30 | + image's file extension is changed to this type |
| 31 | +
|
| 32 | + `img_height`:`int` -> Defaults to `200`, If provided the image is |
| 33 | + resized to this `height` |
| 34 | +
|
| 35 | + `img_width`:`int` -> Defaults to `200`, If provided the image is |
| 36 | + resized to this `width` |
| 37 | +
|
| 38 | + * `returns` : `bool` -> `True` if the image was resized else `False` |
| 39 | + """ |
| 40 | + img_path = self.validator.validate_file(img_path) |
| 41 | + image = Image.open(img_path) |
| 42 | + |
| 43 | + if hasattr(settings, 'DEFAULT_EXTENSION'): |
| 44 | + extension = settings.DEFAULT_EXTENSION |
| 45 | + |
| 46 | + resized_image = image.resize( |
| 47 | + (img_width, img_height), Image.ANTIALIAS) |
| 48 | + |
| 49 | + if extension: |
| 50 | + extension = extension.lower() if extension.startswith( |
| 51 | + '.') else '.' + extension.lower() |
| 52 | + img_path = img_path.with_suffix(extension) |
| 53 | + |
| 54 | + # add a new prefix image file before saving |
| 55 | + previous_file_name = img_path.name |
| 56 | + resized_image_name = F'resized_{ previous_file_name }' |
| 57 | + img_format = img_path.suffix.upper()[1:] |
| 58 | + img_path = img_path.with_name(resized_image_name) |
| 59 | + |
| 60 | + if img_path.exists(): |
| 61 | + print_if_verbose(F'Duplicate resized image found at { img_path }') |
| 62 | + |
| 63 | + if not settings.SKIP_EXISTING_FILES: |
| 64 | + print_if_verbose(F'Skipped resizing { img_path.name }\n') |
| 65 | + return img_path |
| 66 | + |
| 67 | + if not settings.OVERRIDE_EXISTING_FILES: |
| 68 | + uuid_appended_name = '-'.join((img_path.stem, uuid4().hex)) |
| 69 | + img_path = img_path.with_stem(uuid_appended_name) |
| 70 | + try: |
| 71 | + resized_image.save(img_path, img_format, quality=90) |
| 72 | + except Exception as e: |
| 73 | + print(F"{e}") |
| 74 | + print_if_verbose( |
| 75 | + F'Resized image - { previous_file_name } ({ img_width }x{ img_height }) (saved at { img_path }) in { img_format } format\n') |
| 76 | + return img_path |
| 77 | + |
| 78 | + def resize_bulk_images(self, *, |
| 79 | + img_paths: Union[Tuple[Path], Tuple[str]] = (), |
| 80 | + img_dir: Union[Path, str] = None, save_as='png', |
| 81 | + extensions: str = None, img_height: int = 200, |
| 82 | + img_width: int = 200, recursive: bool = False) -> None: |
| 83 | + """ |
| 84 | + Resizes image file to the new height and width as well as |
| 85 | + a new extension type if extension is provided |
| 86 | +
|
| 87 | + `img_paths`:`Tuple[Path]` | `Tuple[str]` -> Tuple containing paths |
| 88 | + or string representation of the image paths to be processed |
| 89 | +
|
| 90 | + `img_dir`:`Path | str` -> Folder containing images to be processed |
| 91 | +
|
| 92 | + `extensions`:`str` -> Defaults to `None`, If it is provided the |
| 93 | + images with file extension type(s) are resized |
| 94 | +
|
| 95 | + `img_height`:`int` -> Defaults to `200`, If provided the image is |
| 96 | + resized to this `height` |
| 97 | +
|
| 98 | + `img_width`:`int` -> Defaults to `200`, If provided the image is |
| 99 | + resized to this `width` |
| 100 | +
|
| 101 | + `returns` : `int` -> Total number of images successfully resized |
| 102 | + """ |
| 103 | + |
| 104 | + self.validator.validate_path_args(img_paths=img_paths, img_dir=img_dir) |
| 105 | + |
| 106 | + # we use the img_paths argument if it is provided, |
| 107 | + # use the img_dir if the img_paths is not |
| 108 | + image_paths = img_paths or self.get_paths_from_dir( |
| 109 | + img_dir, extensions=extensions or settings.SUPPORTED_EXTENSIONS, recursive=recursive) |
| 110 | + |
| 111 | + kwargs = { |
| 112 | + 'extension': save_as, |
| 113 | + 'img_height': img_height, |
| 114 | + 'img_width': img_width |
| 115 | + } |
| 116 | + |
| 117 | + threads: list[Thread] = [] |
| 118 | + thread: Thread |
| 119 | + |
| 120 | + for img_path in image_paths: |
| 121 | + thread = Thread(target=self.resize_image, |
| 122 | + args=(img_path,), kwargs=kwargs) |
| 123 | + thread.start() |
| 124 | + threads.append(thread) |
| 125 | + |
| 126 | + for thread in threads: |
| 127 | + thread.join() |
0 commit comments