supress issues w/ news images compression

This commit is contained in:
Kuroshini 2020-01-14 17:32:13 +03:00
parent 80dec0b6ee
commit 3f19699e1d
2 changed files with 9 additions and 2 deletions

View File

@ -29,9 +29,14 @@ class Command(BaseCommand):
def optimize(self, text, max_size, max_quality):
"""optimize news images"""
for image in get_url_images_in_text(text):
size, width, height = get_image_meta_by_url(image)
try:
size, width, height = get_image_meta_by_url(image)
except IOError as ie:
self.stdout.write(self.style.NOTICE(f'{ie}\n'))
continue
if size < max_size:
self.stdout.write(self.style.SUCCESS(f'No need to compress images size is {size / 1024}Mb\n'))
continue
percents = round(max_size / (size * 0.01))

View File

@ -121,6 +121,7 @@ def absolute_url_decorator(func):
return f'{settings.MEDIA_URL}{url_path}/'
else:
return url_path
return get_absolute_image_url
@ -177,7 +178,8 @@ def get_url_images_in_text(text):
"""Find images urls in text"""
return re.findall(r'(?:http:|https:)?//.*\.(?:png|jpg|svg)', text)
def get_image_meta_by_url(url) -> (int, int, int, str):
def get_image_meta_by_url(url) -> (int, int, int):
"""Returns image size (bytes, width, height)"""
image_raw = requests.get(url)
image = Image.open(BytesIO(image_raw.content))