设置图像大小限制和调整图像的大小如果需要
我使用django-ckeditor
在我的形式和widget=CKEditorUploadingWidget()
一些,所以我可以上传图像,工作正常,但现在我需要设置1MB作为图像的大小限制。设置图像大小限制和调整图像的大小如果需要
我的第一个问题是我该如何限制尺寸?如果可行我宁愿配置django-ckeditor
配置的限制,这是可行的吗?或者我必须在服务器中完成。
我的第二个问题是如果图像大于1MB我需要调整图像的大小POST
可能会减少一半的重量和高度,如果还有更大的1mb重复该过程直到大小小于1mb,要点是用户只需选择图像,应用程序就可以完成所有的工作,而用户不需要自己调整图像大小。
我的最后一个问题是,如果我需要做的这一切proccess在客户端,什么是更好的,使用JQuery
或Python
与Pillow
并在视图proccess的形象呢?
我真的失去了这一点,任何帮助真的令人失望。
有很多谈话可以进入这个。另一方面,对于图像大小检查而言,基本上有两个独立的问题。 1)客户端和2)服务器端。所以让我们分手吧。
服务器端
这是两者中最重要的部分。是的,客户端可以帮助缩小图像的大小或通知用户他们尝试上传的图片太大,但最终您希望服务器决定什么是可接受的。
因此,在Django中,你可以做一些事情。
1)限制文件大小 - 在你的设置,你可以把下面的代码
# Add to your settings file
MAX_UPLOAD_SIZE = "1048576"
使图像尺寸检查类似下面,并运行它以检查“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
这将让上传的文件大小超过1MB,期。
2)调整图像大小 - 使用PIL(Pillow),调整图像大小。
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.
3)有损compresss图像
# 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
客户机端
真的,客户端仅使事情对于用户而言更简单。你可以尝试在客户端实现这些东西,但是如果你依赖它,总会有人绕过你的客户端设置并上传一个10TB大小的“图像”(有些人只是想看世界烧)。
1)调整大小或压缩 - 与上面相同,但使用Javascript或Jquery。
2)cropping - JCrop是我以前使用过的库。它需要一些工作,但它很有用。您可以帮助用户将图像裁剪为更适合的尺寸,并且可以让他们更好地了解图像如何看待新分辨率。
2)有用的信息 - 如果用户上传的图片太大,请让他们知道。
来源
How to get image size in python-pillow after resize?
How do I resize an image using PIL and maintain its aspect ratio?
How to adjust the quality of a resized image in Python Imaging Library?
谢谢你这么多的解释,是真正的帮助。检查第一个点'MAX_UPLOAD_SIZE =“1048576”或“MAX_UPLOAD_SIZE = 1048576”不起作用我仍然可以上传1mb的较大图像。 –
多大? –
我很快就给出了这个建议。让我做一些改变。 –