2014-02-24 160 views
0

該方案是,客戶端將圖像上傳到我的Django服務,並且Django服務需要將圖像尺寸調整爲600 x 600,並且應該減少圖像大小(以字節爲單位)。Django在調整字體大小時增加了字節大小

這是我使用的代碼:

import StringIO 
from django.core.files.uploadedfile import InMemoryUploadedFile 
image.thumbnail((size, size), Image.ANTIALIAS) 

不過,我發現它有時甚至會增加以字節爲單位的圖像大小。有時客戶端上傳尺寸爲1000 x 1000,尺寸爲80kb的圖片,執行上述線條生成縮略圖後,縮略圖爲600 x 600,尺寸爲130kb。我(壓縮後至少低於80kb)期待像50kb

請幫助

+0

嘗試用[JPEG作家的選項]搞亂(http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html#jpeg),可能降低質量或優化意志幫幫我? –

回答

1

嘗試用這個,可能是這種方法幫助你。

import StringIO 
from PIL import Image 

image_field = self.cleaned_data.get('image_field') 
image_file = StringIO.StringIO(image_field.read()) 
image = Image.open(image_file) 
w, h0 = image.size 

image = image.resize((w/2, h/2), Image.ANTIALIAS) 

image_file = StringIO.StringIO() 
image.save(image_file, 'JPEG', quality=90) 

image_field.file = image_file