from pathlib import Path from django import forms from django.core.exceptions import ValidationError from django.core.files.base import ContentFile from PIL import Image, ImageOps def as_webp(upload): # Validate before decoding pixel data, then respect camera orientation. from .models import validate_image validate_image(upload) dst = ContentFile(b'', name=f'{Path(upload.name).stem}.webp') try: with Image.open(upload) as source: normalized = ImageOps.exif_transpose(source) if normalized.mode not in ('RGB', 'RGBA'): alpha = 'A' in normalized.getbands() or 'transparency' in normalized.info normalized = normalized.convert('RGBA' if alpha else 'RGB') normalized.save(dst, format='WEBP', lossless=True, method=2, icc_profile=source.info.get('icc_profile')) if dst.tell() > 12 * 1024 * 1024: dst.seek(0) dst.truncate() normalized.save(dst, format='WEBP', quality=94, method=2, icc_profile=source.info.get('icc_profile')) dst.size = dst.tell() dst.seek(0) validate_image(dst) except (OSError, ValueError, SyntaxError) as exc: raise ValidationError('The image could not be converted to WebP.') from exc return dst class WebPUploadField(forms.ImageField): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.widget.attrs['data-studio-art'] = '' self.widget.attrs['accept'] = 'image/jpeg,image/png,image/webp' def to_python(self, data): if data is None: return None return as_webp(data) class ShareImageUploadField(WebPUploadField): """Small, widely compatible JPEGs for link crawlers.""" def to_python(self, data): if data is None: return None from .models import validate_image validate_image(data) dst = ContentFile(b'', name='share-image.jpg') try: with Image.open(data) as source: image = ImageOps.exif_transpose(source) image.thumbnail((1600, 1600)) rgba = image.convert('RGBA') canvas = Image.new('RGB', rgba.size, '#ffffff') canvas.paste(rgba, mask=rgba.getchannel('A')) canvas.save(dst, 'JPEG', quality=88, optimize=True) dst.size = dst.tell() dst.seek(0) return dst except (OSError, ValueError, SyntaxError) as exc: raise ValidationError('The share image could not be converted.') from exc