How to set the maximum image size to upload image in django-ckeditor?
Asked Answered
I

2

9

I am using django-ckeditor for my project to upload image along with text content.
I used body = RichTextUploadingField(blank=True, null=True) in model. Now I want to restrict the user to upload large size images in content or larger than predefined maximum height/width. I want the uploaded images in content of particular height/weight and size like less then 1mb.

How can I predefine maximum image height and width as well as maximum image size limit?

Is there any way to define it from django-ckeditor configuration?

Or How to resize the uploaded images from content at backend after user submitted the form?

Here is my models.py:

class Post(models.Model):
    STATUS_CHOICES = {
      ('draft', 'Draft'),
      ('published', 'Published'),
    }
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250, unique=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = RichTextUploadingField(blank=True, null=True)
    status = models.CharField(max_length=10,
                             choices=STATUS_CHOICES,
                             default='draft')

I tried a lot to solve it but failed.Any suggetion to solve the issue? Thanks in advance.

Ingulf answered 28/7, 2020 at 14:14 Comment(0)
O
0

You can set CKEDITOR_THUMBNAIL_SIZE in setting.py

CKEDITOR_THUMBNAIL_SIZE = (500, 500)

With the pillow backend, you can change the thumbnail size with the CKEDITOR_THUMBNAIL_SIZE setting (formerly THUMBNAIL_SIZE). Default value: (75, 75)

With the pillow backend, you can convert and compress the uploaded images to jpeg, to save disk space. Set the CKEDITOR_FORCE_JPEG_COMPRESSION setting to True (default False) You can change the CKEDITOR_IMAGE_QUALITY setting (formerly IMAGE_QUALITY), which is passed to Pillow:

The image quality, on a scale from 1 (worst) to 95 (best). The default is 75. Values above 95 should be avoided; 100 disables portions of the JPEG compression algorithm and results in large files with hardly any gain in image quality.

This feature is disabled for animated images.

check official doc. https://github.com/django-ckeditor/django-ckeditor/blob/master/README.rst

Ozoniferous answered 3/6, 2021 at 13:28 Comment(0)
O
0

I think there should be a way to resize the picture on uploading. But to be honest I didn't find nor in documentation neither by debugging.

However, I can suggest you a work-around to post-process all the images inside the content upon saving of Post model.

models.py

from django.conf import settings
from PIL import Image

def resize_image(filename):
    """
    here goes resize logic.
    For example, I've put 50% of current size if width>=900.
    Might be something more sophisticated
    """
    im = Image.open(filename)
    width, height = im.size
    if width >= 500:
        im = im.resize((int(width * 0.5), int(height * 0.5)))
        im.save(filename)

class Post(models.Model):
    ...
    body = RichTextUploadingField(blank=True, null=True)
    ...

    def save(self, *args, **kwargs):
        for token in self.body.split():
            # find all <img src="/media/.../img.jpg">
            if token.startswith('src='):
                filepath = token.split('=')[1].strip('"')   # get path of src
                filepath = filepath.replace('/media', settings.MEDIA_ROOT)  # resolve path to MEDIA_ROOT
                resize_image(filepath)  #do resize in-place

        super().save(*args, **kwargs)

The solution is not super nice because it resizes picture only after it was uploaded.

Probably the library itself should have some kind of exit-point/callback for image pre-processing when uploaded.

Osman answered 3/6, 2021 at 12:38 Comment(0)
O
0

You can set CKEDITOR_THUMBNAIL_SIZE in setting.py

CKEDITOR_THUMBNAIL_SIZE = (500, 500)

With the pillow backend, you can change the thumbnail size with the CKEDITOR_THUMBNAIL_SIZE setting (formerly THUMBNAIL_SIZE). Default value: (75, 75)

With the pillow backend, you can convert and compress the uploaded images to jpeg, to save disk space. Set the CKEDITOR_FORCE_JPEG_COMPRESSION setting to True (default False) You can change the CKEDITOR_IMAGE_QUALITY setting (formerly IMAGE_QUALITY), which is passed to Pillow:

The image quality, on a scale from 1 (worst) to 95 (best). The default is 75. Values above 95 should be avoided; 100 disables portions of the JPEG compression algorithm and results in large files with hardly any gain in image quality.

This feature is disabled for animated images.

check official doc. https://github.com/django-ckeditor/django-ckeditor/blob/master/README.rst

Ozoniferous answered 3/6, 2021 at 13:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.