2012-11-08 83 views
0

我想在將模型保存到磁盤之前縮放ImageField,但以某種方式獲取不可讀的圖像。我們的目標是在不將其保存到磁盤的情況下進行擴展。在保存到磁盤之前縮放Django ImageField

這是我嘗試迄今:

IMAGE_MAX_SIZE = 800, 800 
class Picture(models.Model): 
    ... 
    image = models.ImageField(upload_to='images/%Y/%m/%d/') 

    # img is a InMemoryUploadedFile, received from a post upload 
    # removing the scale function results in a readable image 
    def set_image(self, img): 
     self.image = img 
     self.__scale_image() 

    def __scale_image(self): 
     img = Image.open(StringIO(self.image.read())) 
     img.thumbnail(IMAGE_MAX_SIZE, Image.ANTIALIAS) 
     imageString = StringIO() 
     img.save(imageString, img.format) 
     self.image.file = InMemoryUploadedFile(imageString, None, self.image.name, self.image.file.content_type, imageString.len, None) 

我沒有得到一個錯誤,但產生的圖像無法正確顯示。任何想法如何糾正這一點?

感謝 西蒙

回答

1

我很接近,但不是那裏。此功能現在可以正常工作,圖像在縮放過程中的任何點都不會保存到光盤。

IMAGE_MAX_SIZE = 800, 800 
class Picture(models.Model): 
    ... 
    image = models.ImageField(upload_to='images/%Y/%m/%d/') 

    # img is a InMemoryUploadedFile, received from a post upload 
    def set_image(self, img): 
     self.image = img 
     self.__scale_image(self.image, IMAGE_MAX_SIZE) 

    def __scale_image(self, image, size): 
     image.file.seek(0) # just in case 
     img = Image.open(StringIO(image.file.read())) 
     img.thumbnail(size, Image.ANTIALIAS) 
     imageString = StringIO() 
     img.save(imageString, img.format) 

     # for some reason content_type is e.g. 'images/jpeg' instead of 'image/jpeg' 
     c_type = image.file.content_type.replace('images', 'image') 
     imf = InMemoryUploadedFile(imageString, None, image.name, c_type, imageString.len, None) 
     imf.seek(0) 
     image.save(
       image.name, 
       imf, 
       save=False 
      ) 
+0

'出於某種原因,content_type是例如'images/jpeg'而不是'image/jpeg''你能說出原因是什麼嗎?它的工作正常'image/jpeg' –

0

這將更好的主意,使用SORL-thubnail。