image-reducer/image_reducer.py
2023-11-27 11:16:57 +07:00

74 lines
2.1 KiB
Python

import os
import logging
from utils import log
from PIL import Image
def reduce_image_size(
input_path: str,
output_path: str,
target_size: int,
quality: int,
is_optimize: bool = None,
is_resize: bool = False,
):
original_image = Image.open(input_path)
targeted_size = target_size * 1024
allowed_types = (".png", ".jpg", ".jpeg")
get_file_size = os.stat(input_path).st_size
convert_megabytes = get_file_size / (1024 * 1024)
if not output_path.endswith(allowed_types):
raise ValueError("Please ensure the output path is set with the file-type")
if not input_path.endswith(allowed_types):
raise ValueError("Currently, only certain images that can be compressed")
if is_optimize is None:
is_optimize = True
if convert_megabytes >= 80000:
raise OverflowError("File image size is exceeds the limit")
try:
while True:
if not is_resize:
width, height = original_image.size
new_size_wh = (width // 2, height // 2)
original_image.resize(new_size_wh)
original_image.save(output_path, optimize=is_optimize, quality=quality)
# get_new_file_size = os.stat(output_path).st_size
file_size = os.path.getsize(output_path)
new_file_size_as_mb = file_size / (1024**2)
if file_size <= targeted_size:
break
quality -= 5
if quality <= 0:
raise ValueError("Can't achieve with the acceptable target")
return True, original_image.size, new_file_size_as_mb
except Exception as e:
log(f"Something error is occurs: {e}", logging.ERROR)
return False
def delete_file(name: str) -> None:
try:
os.remove(name)
except OSError as e:
log(f"Something error is occurs: {e}", logging.ERROR)
# input_image = "image.png"
# output_image = "reduce_image.png"
# target_size = 2500
# reduce_img, current_size = reduce_image_size(input_image, output_image, target_size, 55)
# if reduce_img:
# print(f"Success, and the current size is {current_size}")
# else:
# print("False")