2012-01-08 85 views
3

我試圖在保存模型實例的同時調整圖像大小。如何在保存之前獲取Django ImageField的內容?

class Picture(models.Model): 
    image_file = models.ImageField(upload_to="pictures") 
    thumb_file = models.ImageField(upload_to="pictures", editable=False) 
    def save(self, force_insert=False, force_update=False): 
    image_object = Image.open(self.image_file.path) 
    #[...] nothing yet 
    super(Picture, self).save(force_insert, force_update) 

問題是在保存模型之前self.image_file.path不存在。它返回一個正確的路徑,但圖像還沒有。由於沒有圖像,我無法在PIL中打開它來調整大小。

我想將縮略圖存儲在thumb_file(另一個ImageField)中,所以我需要在保存模型之前進行處理。

有沒有一種很好的方法來打開文件(也許在內存中獲取tmp圖像對象)還是必須先保存整個模型,調整大小然後再保存?

回答

0

也許你可以直接打開文件和生成的文件句柄傳遞給Image.open

image_object = Image.open(self.image_file.open()) 

對不起,我無法測試,現在。

+4

沒有它不工作,要麼.. > 'NoneType' 對象有沒有屬性 '讀' – JasonTS 2012-01-08 12:49:41

2

我以前this snippet

import Image 

def fit(file_path, max_width=None, max_height=None, save_as=None): 
    # Open file 
    img = Image.open(file_path) 

    # Store original image width and height 
    w, h = img.size 

    # Replace width and height by the maximum values 
    w = int(max_width or w) 
    h = int(max_height or h) 

    # Proportinally resize 
    img.thumbnail((w, h), Image.ANTIALIAS) 

    # Save in (optional) 'save_as' or in the original path 
    img.save(save_as or file_path) 

    return True 

而且在車型:

def save(self, *args, **kwargs): 
    super(Picture, self).save(*args, **kwargs) 
    if self.image: 
     fit(self.image_file.path, settings.MAX_WIDTH, settings.MAX_HEIGHT) 
+1

這樣的作品,但我想將拇指存儲在另一個圖像場中..這就是爲什麼我必須在保存模型之前進行調整大小。 – JasonTS 2012-01-08 14:18:04

+0

沒問題,用名稱前綴在擬合函數中創建新圖像。例如「t_」。並在模型中添加函數到拇指返回路徑。 – 2012-01-08 15:05:17

+0

或使用外部庫,例如:[sorl](https://github.com/sorl/sorl-thumbnail) – 2012-01-08 15:07:58

相關問題