From 6c03c05d906af4dd82ab99d90997b08fe74b7e04 Mon Sep 17 00:00:00 2001 From: Kun Fang Date: Fri, 6 Sep 2024 12:06:53 -0400 Subject: [PATCH] fix: apply flexible compression ratio Refs: #152 --- .../management/commands/download_imgs.py | 40 +++++++++++++++++-- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/web-app/django/VIM/apps/instruments/management/commands/download_imgs.py b/web-app/django/VIM/apps/instruments/management/commands/download_imgs.py index 1f4d503..0aaf4d8 100644 --- a/web-app/django/VIM/apps/instruments/management/commands/download_imgs.py +++ b/web-app/django/VIM/apps/instruments/management/commands/download_imgs.py @@ -46,13 +46,47 @@ def _save_image_as_png(self, img_content, url, save_path): except IOError as e: self.stderr.write(f"Failed to save image from {url}: {e}") - def create_thumbnail(self, image_path, thumbnail_path, compression_ratio=0.35): + def calculate_compression_ratio(self, original_width, original_height): + """ + Calculate a flexible compression ratio based on the original dimensions of an image. + + Parameters: + original_width (int): The width of the original image. + original_height (int): The height of the original image. + + Returns: + float: The compression ratio. + """ + # Determine the larger dimension to base compression on (could be width or height) + max_dimension = max(original_width, original_height) + + # Set a target size for compression based on original dimensions + if max_dimension > 4000: + # Large images (e.g., 4K or higher): compress significantly + compression_ratio = 0.2 # 20% of the original size + elif max_dimension > 2000: + # Medium-large images: moderate compression + compression_ratio = 0.5 # 50% of the original size + elif max_dimension > 1000: + # Medium images: light compression + compression_ratio = 0.75 # 75% of the original size + else: + # Small images: minimal compression + compression_ratio = 0.9 # 90% of the original size + + return compression_ratio + + def create_thumbnail(self, image_path, thumbnail_path): """Create a thumbnail of an image.""" try: with Image.open(image_path) as original_img: + original_width, original_height = original_img.size + compression_ratio = self.calculate_compression_ratio( + original_width, original_height + ) new_size = ( - int(original_img.width * compression_ratio), - int(original_img.height * compression_ratio), + int(original_width * compression_ratio), + int(original_height * compression_ratio), ) original_img.thumbnail(new_size) original_img.save(thumbnail_path, "PNG")