如果需要,设置图像大小限制并调整图像大小

M. *_*Gar 3 python django jquery ckeditor django-ckeditor

我在我的表单中使用django-ckeditor了一些<textarea>并使用,widget=CKEditorUploadingWidget()以便我可以上传图像,这工作正常,但现在我需要将 1mb 设置为图像的大小限制。

我的第一个问题是如何限制大小?如果可能的话,我更喜欢在配置中配置限制django-ckeditor,这可能吗?或者我必须在服务器中进行。

我的第二个问题是,如果图像大于 1mb,我需要调整图像的大小,POST可能会将重量和高度减半,如果仍然大于 1mb,请重复该过程,直到大小小于 1mb,关键是用户只需选择图像,应用程序即可完成所有操作,用户无需自行调整图像大小。

我的最后一个问题是,如果我需要在客户端完成所有这些过程,有什么更好的方法,使用JQueryPython使用Pillow并处理视图中的图像?

我真的失去了这个,任何帮助真的很感激。

Phi*_*tin 8

有很多对话可以涉及到这一点。另一方面,担心图像大小检查基本上有两个独立的问题。1)客户端和 2)服务器端。所以让我们打破它。

服务器端

这是两者中最重要的部分。是的,客户端可以帮助减小图像的大小或通知用户他们尝试上传的图像太大,但最终您希望服务器决定什么是可接受的。

因此,在 Django 中,您可以做一些事情。

1)限制文件大小- 在您的设置中,您可以放置​​以下代码

# Add to your settings file
MAX_UPLOAD_SIZE = "1048576"
Run Code Online (Sandbox Code Playgroud)

制作一个像下面这样的图像大小检查器,并运行它来检查“image_field”的大小(名称可能会改变)。如果“image_field”太大,此代码将返回验证错误。

#Add to a form containing a FileField and change the field names accordingly.
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

def check_image_field_size(self):
    content = self.cleaned_data.get('image_field')
    if content._size > settings.MAX_UPLOAD_SIZE:
        raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(content._size)))
    return content
Run Code Online (Sandbox Code Playgroud)

来源

这将使上传的文件大小不超过 1MB,期间。

2)调整图像大小- 使用 PIL(枕头),调整图像大小。

import StringIO
from PIL import Image
from io import BytesIO

# get the image data from upload
image_field = self.cleaned_data.get('image_field')
image_file = StringIO.StringIO(image_field.read())
image = Image.open(image_file)

# like you said, cut image dimensions in half
w, h = image.size
image = image.resize((w/2, h/2), Image.ANTIALIAS)

# check if the image is small enough 
new_img_file = BytesIO()
image.save(new_img_file, 'png')
image_size = new_img_file.tell() 

# if the image isn't small enough, repeat the previous until it is.
Run Code Online (Sandbox Code Playgroud)

3)有损压缩图像

 # assuming you already have the PIL Image object (im)
 quality_val = 90
 new_img_file = BytesIO()
 im.save(filename, 'JPEG', quality=quality_val)
 image_size = new_img_file.tell()
 # if image size is too large, keep repeating
Run Code Online (Sandbox Code Playgroud)

客户端

真的,客户端只会让用户的事情变得更简单。你可以尝试在客户端实现这些东西,但如果你依赖它,总是有可能有人绕过你的客户端设置并上传一个 10TB 大小的“图像”(有些人只是想看世界燃烧)。

1) 调整大小或压缩 - 同上,但使用 Javascript 或 Jquery。

2)cropping - JCrop是我之前用过的一个库。这需要一些工作,但它很有用。您可以帮助用户将图像裁剪为更合适的尺寸,并赋予他们更多的权力来控制图像在新分辨率下的外观。

2) 有用的消息 - 如果用户上传的图片太大,请告知他们。

来源

调整大小后如何在python-pillow中获取图像大小?

如何使用 PIL 调整图像大小并保持其纵横比?

如何在 Python Imaging Library 中调整调整大小的图像的质量?