Python Django:图像大小调整&;压缩
我正在做一个Django项目,用户可以上传图片 以下是观点:Python Django:图像大小调整&;压缩,python,django,Python,Django,我正在做一个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
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\u image
文件夹中时,它会为每个新图像创建一系列子文件夹,并将该图像保存在单独的文件夹中
因此,profile\u image
文件夹如下所示
profile_image
my_image.png
----profile_image
new_image.png
--------profile_image
all_image.png
------------profile_image
images.png
----------------profile_image
picture.png
--------------------profile_image
another_pic.png
& so on . . .
我们如何将所有新图像保存在一个文件夹中并防止形成这些子文件夹?试试这个profile=models.ImageField(上传到@profile\u image/,blank=True)@Exprator先生,它仍在自己创建子文件夹。我该怎么办?在上传到中的配置文件图片后使用该图片,然后再试一次once@Exprator是的,先生,我添加了/&然后运行makemigrations&migrate。但还是造成了同样的错误。先生,刚才我从模型中删除了整个压缩和调整大小的代码&现在一切正常。但是我需要调整大小和压缩功能,我不知道这段代码中的问题在哪里:(.你能找到它吗?使用
os.path.split
从路径中获取文件名。temp_name=os.path.split(self.profile.name)[1]#这将提供文件名
。