2015-06-23 46 views
1

我是Python世界的新手。對於一個項目(使用django),我使用PIL庫將.gif文件轉換爲.jpg文件。但是,當模型的保存方法運行時,它會拋出'IOError在...不能像JPEG一樣寫模式P'Django在嘗試將.gif文件轉換爲.jpeg時拋出IO錯誤

這是我的Model類。請給我一個解決方案。提前致謝。

class ImageArtwork(models.Model): 
    filepath = 'art_images/' 
    artwork = models.ForeignKey(Artwork, related_name='images') 
    artwork_image = models.ImageField(_(u"Dieses Bild hinzufügen: "), upload_to=filepath) 
    image_medium = models.CharField(max_length=255, blank=True) 
    image_thumb = models.CharField(max_length=255, blank=True) 
    uploaded_at = models.DateTimeField(auto_now_add=True) 

    def get_thumb(self): 
     return "/media/%s" % self.image_thumb 

    def get_medium(self): 
     return "/media/%s" % self.image_medium 

    def get_original(self): 
     return "/media/%s" % self.artwork_image 

    def save(self): 
     sizes = {'thumbnail': {'height': 50, 'width': 50}, 'medium': {'height': 300, 'width': 300}, } 

     # Check if the number of images for the artwork has already reached maximum limit 

     if ImageArtwork.objects.filter(artwork=self.artwork).count() < 6: 
      super(ImageArtwork, self).save() 
      photopath = str(self.artwork_image.path)  # this returns the full system path to the original file 
      im = Image.open(photopath)  # open the image using PIL 

      # pull a few variables out of that full path 
      extension = photopath.rsplit('.', 1)[1]  # the file extension 
      filename = photopath.rsplit('/', 1)[1].rsplit('.', 1)[0] # the file name only (minus path or extension) 
      fullpath = photopath.rsplit('/', 1)[0]  # the path only (minus the filename.extension) 

      # use the file extension to determine if the image is valid before proceeding 
      if extension.lower() not in ['jpg', 'jpeg', 'gif', 'png']: 
       return 
      im = ImageOps.fit(im, (sizes['medium']['width'], sizes['medium']['height']), Image.ANTIALIAS)  # create medium image 
      medname = filename + "_" + str(sizes['medium']['width']) + "x" + str(sizes['medium']['height']) + ".jpg" 
      im.save(fullpath + '/' + medname) 
      self.image_medium = '/media/' + self.filepath + medname 
      im = ImageOps.fit(im, (sizes['thumbnail']['width'], sizes['thumbnail']['height']), Image.ANTIALIAS)  # create thumbnail 
      thumbname = filename + "_" + str(sizes['thumbnail']['width']) + "x" + str(
       sizes['thumbnail']['height']) + ".jpg" 
      im.save(fullpath + '/' + thumbname) 
      self.image_thumb = '/media/' + self.filepath + thumbname 
      super(ImageArtwork, self).save() 

     else: 
      pass 

回答

4

不能寫P模式下爲JPEG

這不是一個Django的問題,這是一個影像庫約束。

P代表paletted。寫入JPEG時,PIL會嘗試從原始圖像保留顏色模式。由於JPEG僅支持「TrueColor」(即RGB)圖像,因此在轉換(調色板)GIF文件時會出現此錯誤。

保存爲JPEG時,請務必將圖像轉換爲RGB:

im.convert('RGB').save(fullpath + '/' + medname)