2013-04-20 55 views
3

我有一個稱爲圖片的模型。當圖像上傳到此模型中時,它將在保存前自動重新調整大小。Django在不同的模型字段中保存圖片

我的主要目標是要重新大小的上傳圖像分成2個獨立的圖像。所以我可以將它用於不同的目的,如小圖片和大圖片。所以我爲了達到這個目標所做的是創造另一個叫做small的領域。代表小圖片。

我有2個功能叫做下保存和小我的模型。這些功能會自動重新調整圖像的大小。

我的計劃是,當我上傳的圖像模型。我的保存功能會自動調整圖像大小並將其保存到圖像文件夾中,但我怎樣才能讓我的小功能從圖像字段中抓取圖像,以便調整大小並將其保存到我的小字段中。

總結大勢已去,它只是一個retrieveing上傳圖片並調整兩個領域的形象。

class Picture(models.Model): 
    user = models.ForeignKey(User) 
    small = models.ImageField(upload_to="small/",blank=True,null=True) 
    image = models.ImageField(upload_to="images/",blank=True) 

    def save(self , force_insert=False,force_update=False): 
     super (Picture,self).save(force_insert,force_update) 

     pw = self.image.width 
     ph = self.image.height 
     mw = 500 
     mh = 500 

     if (pw > mw) or (ph > mh): 
      filename = str(self.image.path) 
      imageObj = img.open(filename) 
      ratio = 1 

      if (pw > mw): 
       ratio = mw/float(pw) 
       pw = mw 
       ph = int(math.floor(float(ph)* ratio)) 
      if (ph > mh): 
       ratio = ratio * (mh /float(ph)) 
       ph = mh 
       pw = int(math.floor(float(ph)* ratio)) 

      imageObj = imageObj.resize((pw,ph),img.ANTIALIAS) 
      imageObj.save(filename) 

    def save(self , force_insert=False,force_update=False): 
     super (Picture,self).save(force_insert,force_update) 

     pw = self.image.width 
     ph = self.image.height 
     mw = 300 
     mh = 300 

     if (pw > mw) or (ph > mh): 
      filename = str(self.image.path) 
      imageObj = img.open(filename) 
      ratio = 1 

      if (pw > mw): 
       ratio = mw/float(pw) 
       pw = mw 
       ph = int(math.floor(float(ph)* ratio)) 
      if (ph > mh): 
       ratio = ratio * (mh /float(ph)) 
       ph = mh 
       pw = int(math.floor(float(ph)* ratio)) 

      imageObj = imageObj.resize((pw,ph),img.ANTIALIAS) 
      imageObj.save(filename) 

如果這沒有任何意義,提醒我,讓我可以修改它

+2

爲什麼不使用[SORL-縮略圖(http://sorl-thumbnail.readthedocs.org/en/latest/examples.html)呢? – Darwin 2013-04-24 18:31:02

+0

@Darwin偉大的答案, – donkeyboy72 2013-05-01 07:25:53

回答

1

您可以創建自定義字段(繼承的ImageField),或創建一個pre_save信號處理上載。

from django.db.models.signals import pre_save 
from django.dispatch import receiver 
from myapp.models import MyModel 


class MyModel(models.Model): 
    # other fields 
    image = MyCustomImageField(sizes=(('small', '300x300'), ('large', '500x500'))) 

的信號

@receiver(pre_save, sender=MyModel) 
def process_picture(sender, **kwargs): 
    # do resizing and storage stuff 

更多關於signals和定製fields

A working example of a custom ImageField.

+2

這只是用作設置可以定義你想已經創建了縮略圖大小的屬性。您只需要一個功能來創建縮略圖。看看我發佈的工作示例。 – 2013-04-20 12:27:43

+1

@Jacob,它確實是你正在學習的Python,Django只是使用Python代碼。 [示例](https://github.com/django-lfs/lfs/blob/master/core/fields/thumbs.py)有很好的文檔記錄,如果你要複製並粘貼它,它可能會工作在框。仔細閱讀,你應該有一個基本的瞭解。 – 2013-04-20 12:40:30

+1

一個字段只是一個python類。 [97線](https://github.com/django-lfs/lfs/blob/master/core/fields/thumbs.py#L97)在本例中限定了自定義字段。 – 2013-04-20 12:43:17

相關問題