2013-02-28 159 views
4

我在我的models.py以下視野(見下面的代碼)的Django ImageField的設置一個固定的寬度和高度

我想設置一個固定的寬度和圖像的高度,其始終100x100px

下面的代碼是已經在系統中,我不知道如何通過寬度和高度,或者如果此代碼可用於設置寬度和高度爲固定大小。

image = models.ImageField(
     upload_to="profiles", 
     height_field="image_height", 
     width_field="image_width", 
     null=True, 
     blank=True, 
     editable=True, 
     help_text="Profile Picture", 
     verbose_name="Profile Picture" 
    ) 
    image_height = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100") 
    image_width = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100") 
+0

是否要調整圖像下來時,它的第一個上傳或只是總是在100x100的顯示呢?另外,你確定這些圖像的寬高比都是1:1嗎?如果不是,則可能需要調整上傳大小並將尺寸較大的尺寸設置爲100,並保持寬高比。 – Tom 2013-02-28 16:37:32

+0

我希望圖片在上傳到100x100時不會縮小顯示尺寸,對不起,我應該明確說明。 – jason 2013-02-28 16:38:52

+0

可能想取消下面的答案。 [這個鏈接](http://davedash.com/2009/02/21/resizing-image-on-upload-in-django/)應該告訴你如何在視圖中完成這個[SO線程](http ://stackoverflow.com/questions/623698/resize-image-on-save)提供了另一種方法。我通常在模型的save()方法中執行此操作。 – Tom 2013-02-28 20:06:13

回答

4
class ModelName(models.Model):  
    image = models.ImageField(
     upload_to="profiles", 
     null=True, 
     blank=True, 
     editable=True, 
     help_text="Profile Picture", 
     verbose_name="Profile Picture" 
    ) 
    image_height = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100") 
    image_width = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100") 

    def __unicode__(self): 
     return "{0}".format(self.image) 

    def save(self): 
     if not self.image: 
      return    

     super(ModelName, self).save() 
     image = Image.open(self.photo) 
     (width, height) = image.size  
     size = (100, 100) 
     image = image.resize(size, Image.ANTIALIAS) 
     image.save(self.photo.path) 
+0

我不能將上傳的圖像大小更改爲100x100嗎?我應該說清楚,對不起。 – jason 2013-02-28 16:37:49