python把图片另存为_PIL将图像另存为.jpg无效

在尝试使用Python的PIL库调整图像尺寸并保存为.jpg格式时遇到问题,其他格式正常。代码中通过Image.open()打开图片,使用thumbnail()方法调整尺寸,然后尝试用InMemoryUploadedFile保存,但.jpg格式未成功。可能的原因是PIL库文档中未明确列出JPG格式。寻求解决在自定义用户模型上保存.jpg图像的方法。
摘要由CSDN通过智能技术生成

我试图重写模型的save()方法来调整图像的大小。除保存.jpg图像外,所有格式都有效。它不保存扩展名为.jpg的图像。在

我看了枕头文档,没有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或。。。在

感谢任何帮助:)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值