如何设置Djangocketditor中上载图像的最大图像大小?

2024-10-03 02:33:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为我的项目使用django ckeditor上传图像和文本内容。
我曾经 模型中的body=RichTextUploadingField(blank=True,null=True)。 现在,我想限制用户上传内容中的大尺寸图像或大于预定义最大高度/宽度的图像。我希望上传的图像在特定的高度/重量和大小,如低于1mb的内容

如何预定义最大图像高度和宽度以及最大图像大小限制?

有没有办法从django ckeditor配置中定义它?

或者在用户提交表单后如何从后端内容调整上传图像的大小?

这是我的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')

我试图解决这个问题,但失败了。有什么建议可以解决这个问题吗? 提前谢谢


Tags: django用户图像trueckeditor内容宽度高度
2条回答

我认为应该有一种方法来调整上传图片的大小。但老实说,我在文档中也没有通过调试找到

但是,我可以建议您在保存post model后对内容中的所有图像进行后期处理

型号.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)

这个解决方案不是很好,因为它只在上传图片后调整图片大小

库本身可能应该有某种退出点/回调,以便在上载时进行图像预处理

您可以在setting.py中设置CKEDITOR_THUMBNAIL_SIZE

CKEDITOR_THUMBNAIL_SIZE = (500, 500)

使用pillow后端,您可以使用CKEDITOR_THUMBNAIL_SIZE设置(以前的缩略图大小)更改缩略图大小。默认值:(75, 75)

通过pillow后端,您可以将上传的图像转换并压缩为jpeg格式,以节省磁盘空间。将CKEDITOR_FORCE_JPEG_COMPRESSION设置设置为True(默认值False)。您可以更改CKEDITOR_IMAGE_QUALITY设置(以前为IMAGE_QUALITY),该设置将传递给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.

对于动画图像,此功能已禁用

检查官方文件https://github.com/django-ckeditor/django-ckeditor/blob/master/README.rst

相关问题 更多 >