2013-03-01 44 views
1

Django的新手:)Django的PIL錯誤使用S3

我使用S3存儲通過封裝django-storages閱讀文件。這似乎工作完美,當我上傳/通過管理更新的新形象。

models.py(像場)

image = models.ImageField(
     upload_to=path_and_rename("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") 

然後我決定,我想調整在上傳的圖片中加入上保存覆蓋方法如下代碼,以便嘗試...

def save(self, *args, **kwargs): 


     if not self.id and not self.image: 
      return 

     super(Profile, self).save(*args, **kwargs) 


     image = Image.open(self.image).seek(0) 
     (width, height) = image.size 
     size = (100, 100) 
     image = image.resize(size, Image.ANTIALIAS) 
     image.save(self.image.path) 

這是問題所在,這給出了以下錯誤....

無法識別圖像文件

我昨天然後貼在棧上的一個問題(我刪除)並鏈接到這個答案Django PIL : IOError Cannot identify image file我八九不離十瞭解用戶(因爲圖像還沒有上傳不能讀它尚未)。 但我不知道,這是我的問題!當我得到的錯誤無法識別圖像文件我可以看到原來的文件實際上已被上傳到S3 (當然沒有調整大小)

記住我是一個新手任何人都可以修改我的例子保存方法(解釋)一個辦法來解決這個問題?即一種方式來rezise新形象爲100x100的上傳?

非常感謝

回答

6

使用存儲讀取如果已經寫好然後調整文件....

def save(self, *args, **kwargs): 
     if not self.id and not self.image: 
      return 

     super(Profile, self).save(*args, **kwargs) 


     import urllib2 as urllib 
     from cStringIO import StringIO 
     from django.core.files.uploadedfile import SimpleUploadedFile 

     '''Open original photo which we want to resize using PIL's Image object''' 
     img_file = urllib.urlopen(self.image.url) 
     im = StringIO(img_file.read()) 
     resized_image = Image.open(im) 




     '''Convert to RGB if necessary''' 
     if resized_image.mode not in ('L', 'RGB'): 
      resized_image = resized_image.convert('RGB') 

     '''We use our PIL Image object to create the resized image, which already 
     has a thumbnail() convenicne method that constrains proportions. 
     Additionally, we use Image.ANTIALIAS to make the image look better. 
     Without antialiasing the image pattern artificats may reulst.''' 
     resized_image.thumbnail((100,100), Image.ANTIALIAS) 

     '''Save the resized image''' 
     temp_handle = StringIO() 
     resized_image.save(temp_handle, 'jpeg') 
     temp_handle.seek(0) 

     ''' Save to the image field''' 
     suf = SimpleUploadedFile(os.path.split(self.image.name)[-1].split('.')[0], 
           temp_handle.read(), content_type='image/jpeg') 
     self.image.save('%s.jpg' % suf.name, suf, save=True) 
0

如果你希望

image.save(self.image.path) 

工作。你不應該打開它嗎

image = Image.open(self.image.path).seek(0)