保存时重命名和调整django图像大小

jei2mxaa  于 2022-12-30  发布在  Go
关注(0)|答案(1)|浏览(111)

我正在尝试在保存时调整图像大小和重命名图像
问题是,我想调整我的图像大小,以便使它们成为正方形而不拉伸图像,然后将图像的名称更改为随机数。
目前我正在模型中执行此操作:

user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(null=True, blank=True)
    image = models.ImageField(default='/profile_pics/default.jpg',
                              null=True,
                              blank=True,
                              upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self, **kwargs):
        super().save()
        new_name = random.randint(1, 236325984)

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (200, 200)
            img.thumbnail(output_size)

        if img.height < 299 or img.width < 299:
            output_size = (200, 200)
            img.thumbnail(output_size)

        img.save(self.image.path)

我也试着把我的保存函数os.rename改为rename:

new_name = random.randint(1, 236325984)
        name = f'{new_name}.{img.format.lower()}'
        os.rename(self.image.path, os.path.join(os.path.dirname(self.image.path), name))

但这不起作用,并给我一个错误:[Windows错误32]

6kkfgxo0

6kkfgxo01#

import os
from uuid import uuid4

def path_and_rename(path):
    def wrapper(instance, filename):
        ext = filename.split('.')[-1]
        # get filename
        if instance.pk:
            filename = '{}.{}'.format(instance.pk, ext)
        else:
            # set filename as random string
            filename = '{}.{}'.format(uuid4().hex, ext)
        # return the whole path to the file
        return os.path.join(path, filename)
    return wrapper

并将其添加到图像字段

image = models.ImageField(upload_to=path_and_rename('upload/here/'), ...)

相关问题