25
我有一些奇怪的問題與PIL不調整圖像大小。PIL Image.resize()不調整圖片大小
def handle_uploaded_image(i, u):
# resize image
from PIL import Image
img = Image.open(i)
if img.mode not in ('L', 'RGB'):
img = img.convert('RGB')
width, height = img.size
if width == height:
img.thumbnail(settings.THUMB_SIZE, Image.ANTIALIAS)
elif width > height:
ratio = floor(width/height)
newwidth = ratio * 150
newwidthhalf = floor(newwidth/2)
img.resize((newwidth, 150), Image.ANTIALIAS)
box = 1
img.crop((newwidthhalf, 0, 150, 150))
elif height > width:
ratio = floor(height/width)
newheight = ratio * 150
newheighthalf = floor(newheight/2)
img.resize((150, newheight), image.ANTIALIAS)
box = 1
img.crop((0, newheighthalf, 150, 150))
path = '/'.join([settings.MEDIA_ROOT, 'users', u.username, 'mugshotv2.jpg'])
img.save(path, format='JPEG')
此代碼運行沒有任何錯誤,併產生我的名字命名mugshotv2.jpg圖像在正確的文件夾,但它並沒有調整其大小。它做了一些事情,因爲圖片的大小從120 kb下降到20 kb,但尺寸保持不變。
也許你也可以建議將圖像裁剪成較少代碼的方塊。我有點認爲Image.thumbnail可以做到這一點,但它所做的只是將圖像的寬度縮放到150 px,並保持高度爲100像素。
Alan。
謝謝!就是這樣。這又是這種愚蠢,容易的錯誤,我經常這樣做:P。再看一遍,我無法理解我自己怎麼不理解它 - 畢竟它是在該死的文檔中。 我想我需要去睡覺。 再次感謝和生病嘗試ImageOps.fit有一天:D – 2009-08-09 20:47:30
@ Zayatzz,所以接受@ Nadia的答案,因爲它解決了你的問題,甚至提供了更好的方法建議! – 2009-08-09 22:15:05
啊..那個奇怪的複選標記.... ohwell。它可以使用一些東西來吸引更多的注意力。 – 2009-08-10 10:07:12