Django:图像大小调整和压缩

2024-06-25 05:24:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个Django项目,用户可以上传图片。在

以下是视图:

class AllPictures(models.Model):
    profile = models.ImageField(upload_to='profile_image', blank=True)

    # But before saving the image i'm compressing & resizing it, here's how
    def save(self, *args, **kwargs):
        if self.profile:
            img = Image.open(self.profile)
            resize = img.resize((240, 240), Image.ANTIALIAS)
            new_image = BytesIO()
            resize.save(new_image, format=img.format, quality=75)
            temp_name = self.profile.name
            self.profile.save(temp_name, content=ContentFile(new_image.getvalue()), save=False)
        super(AllPictures, self).save(*args, **kwargs)

但问题是,当我上传图像而不是直接保存到profile_image文件夹时,它会为每个新图像创建一系列子文件夹,并将该图像保存在单独的文件夹中。在

因此,profile_image文件夹如下所示

^{pr2}$

如何将所有新图像保存在一个文件夹中并防止这些子文件夹的形成?在


Tags: name图像imageself文件夹imgnewmodels