2010-09-08 95 views
1

我想在保存圖像之前調整圖像大小。我在模型上使用了自定義保存方法,但是我遇到了一個問題。模型保存方法。保存前調整圖像大小

這是我現在的代碼:

class UserImages(models.Model): 
    height = models.CharField(blank=True, max_length=100) 
    width = models.CharField(blank=True, max_length=100) 
    image = models.ImageField(upload_to="UserImages/%Y/%m/%d", height_field='height', width_field='width') 
    owner = models.ForeignKey(User) 

    def __unicode__(self): 
     return str(self.image) 
    def save(self, *args, **kwargs): 
     if self.image: 
      filename = str(self.image.path) 
      img = Image.open(filename) 

      if img.mode not in ('L', 'RGB'): 
       img = img.convert('RGB') 

      img = ImageOps.fit(img, (180,240), Image.ANTIALIAS, 0, (0.5, 0.5)) 
      img.save(self.image.path) 
     super(UserImages, self).save(*args, **kwargs) 

這種失敗,並告訴我,該文件無法找到。據我所知,這與現在的圖像只存在於內存中並因此不能像這樣打開一樣。

所以我的問題是:我如何打開圖像從內存並將其保存回內存,所以默認的保存方法可以做它的事情呢?

非常感謝您的幫助,這是推動我逼瘋了:)

回答

1

你需要這樣保存UserImages您嘗試訪問其ImageField之前。

一個實例如何做到這一點可以在該段中找到:

基本上:

super(UserImages, self).save() 

PS。你的模型應該有一個單獨的名字,例如UserImage而不是UserImages

+0

非常感謝。首先想到節約,但後來又忘了。不知道爲什麼。謝謝你的名字。我一直使用複數命名我的所有模型,這個必須通過最後一次檢查:) – 2010-09-08 21:20:34

1

使用Django調整大小

pip install django-resized 

models.py

from django_resized import ResizedImageField 

class MyModel(models.Model): 
    ... 
    image = ResizedImageField(max_width=500, max_height=300, upload_to='whatever') 

欲瞭解更多信息看https://github.com/un1t/django-resized

+0

這似乎是打破文件上傳爲我 – max4ever 2014-06-09 08:39:53

相關問題