2013-06-04 40 views
0

我完全失去了在保存圖像後應如何修改圖像的問題。我有一個模型:使用ImageField保存圖像後修改圖像

class Pic(models.Model): 
    imgfile = FaceChopField(upload_to='img/%m/%d') 

該圖像上傳就好了。我已經查找了這個問題,我發現了一些片段和類似的問題,但我仍然非常困惑。是的,我經歷了一系列關於這種混亂/問題的搜索。

有什麼辦法,我可以只:

  1. 訪問已保存的圖像目錄。
  2. 找到名稱/目錄上傳的圖片。
  3. 在圖像上運行我的modify_image(文件名)。
  4. 將修改後的圖像保存在其他目錄中。

我已經通過Django網站上關於管理文件的文檔瞭解了一段時間,並嘗試了不同的解決方案,我已經鑽了一堆StackOverflow。也許,我所要求的只是對前述內容的一種簡單的方法。如果太麻煩了,你甚至不需要向我展示任何代碼。我只是處於虧損狀態,我不知道我現在在做什麼,所以一些解決方案的算法佈局會很好。謝謝。


這是我當前的嘗試:

class FaceChopFieldFile(ImageFieldFile): 
    def __init__(self, *args, **kwargs): 
     super(FaceChopFieldFile, self).__init__(*args, **kwargs) 

    def save(self): 
     super(FaceChopFieldFile, self).save() 
     image_content = facechop(self.path) #my image modification function 

     self.storage.save(self.path, image_content) 


class FaceChopField(ImageField): 
    attr_class = FaceChopFieldFile  


class Pic(models.Model): 
    imgfile = FaceChopField(upload_to='img/%m/%d') 

什麼不對?

+1

下面是保存後調整圖像大小的示例:http://djangosnippets.org/snippets/1100/ –

回答

0

我已經解決了我自己的問題。原來我被重寫保存()不正確:

class FaceChopFieldFile(ImageFieldFile): 
    def __init__(self, *args, **kwargs): 
     super(FaceChopFieldFile, self).__init__(*args, **kwargs) 

    def save(self, name, content, save=True): 
     super(FaceChopFieldFile, self).save(name, content, save) 
     image_content = facechop(self.path) #my image modification function 

     self.storage.save(self.path, image_content) 


class FaceChopField(ImageField): 
    attr_class = FaceChopFieldFile 



class Pic(models.Model): 
    imgfile = FaceChopField(upload_to='img/%m/%d') 

的問題是:

def save(self): 
    super(FaceChopFieldFile, self).save() 

所以我把它改爲:

def save(self, name, content, save=True): 
      super(FaceChopFieldFile, self).save(name, content, save) 

這不正是我希望現在就做。

0

你真正需要的是一個掛鉤當對象即將被保存到數據庫時被調用。我所要做的就是讓所有的圖像處理邏輯在覆蓋你的模型的save method。但是,這會降低您網站的用戶體驗。在那種情況下,我建議寫celery task。更好,你可以運行一個periodic task

+0

這完全不能幫助我,對不起。 –