【问题标题】:PIL - saving image as .jpg not workingPIL - 将图像保存为 .jpg 不起作用
【发布时间】:2018-03-11 12:51:28
【问题描述】:

我正在尝试覆盖模型的 save() 方法来调整图像大小。每种格式都有效,除了保存 .jpg 图像时。它不会保存带有 .jpg 扩展名的图像。

我阅读了 Pillow 文档,没有 JPG 格式。

class Business(models.Model):
photo = models.ImageField(_('photo'), storage=OverwriteStorage(),
                          upload_to=image_upload_to, blank=True, null=True)


def save(self, **kwargs):
    """
    Changing dimensions of images if they are to big.
    Set max height or width to 800px depending on the image is portrait or landscape.
    """
    # Opening the uploaded image
    im = Image.open(self.photo)
    print(im)
    output = BytesIO()
    # set the max width or height
    im.thumbnail((800, 800))
    # find the ext of the file
    ext = self.photo.name.split('.')[1].upper()

    if ext in {'JPEG', 'PNG', 'GIF', 'TIFF'}:
        # after modifications, save it to the output
        im.save(output, format=ext, quality=100)
        output.seek(0)
        # change the imagefield value to be the newley modifed image value
        self.photo = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.photo.name.split('.')[0],
                                          'image/jpeg', sys.getsizeof(output), None)
        super(User, self).save()

我不知道我在这里缺少什么。

在自定义用户模型上执行此操作的最佳方法是什么。使用信号,覆盖 ImageField 或 ...

任何帮助表示赞赏:)

【问题讨论】:

    标签: python django pillow


    【解决方案1】:

    您处理了扩展名JPEG,但没有处理JPG

    您可以在if 之前使用类似的东西来处理它:

    if ext == 'JPG':
        ext = 'JPEG'
    

    【讨论】:

      【解决方案2】:

      重要提示:您不能将文件另存为 .jpg

      您必须使用其他扩展名,例如 .jpeg

      示例: 您必须使用您导入的 Image 对象

      from PIL import Image 
      
      def image_ex():
           imagefile = 'images/original-image.jpg'
           new_name = os.path.splitext('{}'.format(filename))[0]+'.jpeg'
      
           Image.open(imagefile).rotate(270).filter(ImageFilter.DETAIL).save(new_name)
      
      image_ex()
      

      这行得通。请记住不要保存为 .jpg 文件扩展名。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-21
        • 2014-03-21
        相关资源
        最近更新 更多