Skip to content

Commit

Permalink
Merge pull request #153 from DDMAL/flex-compress-ratio
Browse files Browse the repository at this point in the history
fix: apply flexible compression ratio
  • Loading branch information
kunfang98927 authored Sep 6, 2024
2 parents 081e07b + 6c03c05 commit 355d5fb
Showing 1 changed file with 37 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down

0 comments on commit 355d5fb

Please sign in to comment.