2016-04-26 124 views
0

我使用django-ckeditor在我的形式和widget=CKEditorUploadingWidget()一些,所以我可以上傳圖像,工作正常,但現在我需要設置1MB作爲圖像的大小限制。設置圖像大小限制和調整圖像的大小如果需要

我的第一個問題是我該如何限制尺寸?如果可行我寧願配置django-ckeditor配置的限制,這是可行的嗎?或者我必須在服務器中完成。

我的第二個問題是如果圖像大於1MB我需要調整圖像的大小POST可能會減少一半的重量和高度,如果還有更大的1mb重複該過程直到大小小於1mb,要點是用戶只需選擇圖像,應用程序就可以完成所有的工作,而用戶不需要自己調整圖像大小。

我的最後一個問題是,如果我需要做的這一切proccess在客戶端,什麼是更好的,使用JQueryPythonPillow並在視圖proccess的形象呢?

我真的失去了這一點,任何幫助真的令人失望。

回答

2

有很多談話可以進入這個。另一方面,對於圖像大小檢查而言,基本上有兩個獨立的問題。 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 

source

這將讓上傳的文件大小超過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?

+0

謝謝你這麼多的解釋,是真正的幫助。檢查第一個點'MAX_UPLOAD_SIZE =「1048576」或「MAX_UPLOAD_SIZE = 1048576」不起作用我仍然可以上傳1mb的較大圖像。 –

+0

多大? –

+0

我很快就給出了這個建議。讓我做一些改變。 –