Created
July 19, 2021 11:15
-
-
Save gassan/3ae020e4d61f187b1fed95a2298bae27 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from wagtail.images.forms import BaseImageForm | |
from .image_utils import resize | |
class ImageForm(BaseImageForm): | |
# store user in __init__ and set default position of watermark | |
def __init__(self, data=None, files=None, **kwargs): | |
file = files and files.get('file', None) | |
already_resized = kwargs.pop('already_resized', False) | |
if not already_resized and file: | |
new_file = resize(file, file.field_name, file.name, file.content_type) | |
if new_file is not None: | |
# if new size < 90% old sizes | |
if new_file.size / file.size < 0.9: | |
files['file'].close() | |
files['file'] = new_file | |
else: | |
files['file'].seek(0) | |
new_file.close() | |
self.user = kwargs.get('user', None) | |
super().__init__(data=data, files=files, **kwargs) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
from io import BytesIO | |
from PIL import Image as PillowImage, ImageDraw, ImageFont | |
from django.core.files.uploadedfile import InMemoryUploadedFile | |
from wagtail.images.models import Filter, Image as WagtailImage | |
def resize(file, field_name, name, content_type): | |
core_image = WagtailImage(file=file) | |
# img = getattr(file, 'image', None) | |
if core_image: | |
image_filter = Filter(spec='max-4096x2304') | |
new_willow = image_filter.run(core_image, BytesIO()) | |
# new_pillow = new_willow.get_pillow_image() | |
new_file = InMemoryUploadedFile( | |
new_willow.f, | |
field_name, # important to specify field name here | |
name, | |
content_type, | |
# file.field_name, # important to specify field name here | |
# file.name, | |
# file.content_type, | |
len(new_willow.f.getvalue()), | |
None, | |
{} | |
) | |
new_willow.f.seek(0) | |
# setattr(new_file, 'image', new_pillow) | |
return new_file | |
return None |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WAGTAILIMAGES_IMAGE_FORM_BASE = 'core.forms.ImageForm' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment