From bb8accefbf0e91b1cfff985e4f7140030390df3b Mon Sep 17 00:00:00 2001 From: "a.gorbunov" Date: Mon, 20 Jan 2020 10:25:09 +0000 Subject: [PATCH] optimize fix --- .../commands/collection_optimize_images.py | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/apps/collection/management/commands/collection_optimize_images.py b/apps/collection/management/commands/collection_optimize_images.py index 2b6c9e3d..6da4c04a 100644 --- a/apps/collection/management/commands/collection_optimize_images.py +++ b/apps/collection/management/commands/collection_optimize_images.py @@ -11,19 +11,26 @@ class Command(BaseCommand): SORL_THUMBNAIL_ALIAS = 'collection_image' def handle(self, *args, **options): + max_size = 1048576 + with transaction.atomic(): for collection in Collection.objects.all(): if not image_url_valid(collection.image_url): continue - _, width, height = get_image_meta_by_url(collection.image_url) - sorl_settings = settings.SORL_THUMBNAIL_ALIASES[self.SORL_THUMBNAIL_ALIAS] - sorl_width_height = sorl_settings['geometry_string'].split('x') + size, width, height = get_image_meta_by_url(collection.image_url) - if int(sorl_width_height[0]) > width or int(sorl_width_height[1]) > height: - collection.image_url = get_thumbnail( - file_=collection.image_url, - **settings.SORL_THUMBNAIL_ALIASES[self.SORL_THUMBNAIL_ALIAS] - ).url + if size < max_size: + self.stdout.write(self.style.SUCCESS(f'No need to compress images size is {size / (2 ** 20)}Mb\n')) + continue + + percents = round(max_size / (size * 0.01)) + width = round(width * percents / 100) + height = round(height * percents / 100) + collection.image_url = get_thumbnail( + file_=collection.image_url, + geometry_string=f'{width}x{height}', + upscale=False + ).url collection.save()