Man*_*ble 7 python django image django-models python-imaging-library
当用户从 Django 管理面板上传图像时,我想将图像格式更改为'.webp'。我已经重写了模型的保存方法。Webp 文件在 media/banner 文件夹中生成,但生成的文件未保存在数据库中。我怎样才能做到这一点?
def save(self, *args, **kwargs):
super(Banner, self).save(*args, **kwargs)
im = Image.open(self.image.path).convert('RGB')
name = 'Some File Name with .webp extention'
im.save(name, 'webp')
self.image = im
Run Code Online (Sandbox Code Playgroud)
但是保存模型后,Image 类的实例未保存在数据库中?
我的模型类是:
class Banner(models.Model):
image = models.ImageField(upload_to='banner')
device_size = models.CharField(max_length=20, choices=Banner_Device_Choice)
Run Code Online (Sandbox Code Playgroud)
from django.core.files import ContentFile
Run Code Online (Sandbox Code Playgroud)
如果您已经有了 webp 文件,请读取 webp 文件,将其放入ContentFile()
缓冲区(类似于io.BytesIO
)。然后您可以继续将ContentFile()
对象保存到模型中。不要忘记更新模型字段,并保存模型!
https://docs.djangoproject.com/en/4.1/ref/files/file/
“django-webp-converter 是一个 Django 应用程序,它可以直接将静态图像转换为 WebP 图像,对于不支持的浏览器则回退到原始静态图像。”
它可能也有一些保存功能。
https://django-webp-converter.readthedocs.io/en/latest/
您还以错误的顺序保存,调用的正确顺序super().save()
是在最后。
from django.core.files import ContentFile
from io import BytesIO
def save(self, *args, **kwargs):
#if not self.pk: #Assuming you don't want to do this literally every time an object is saved.
img_io = BytesIO()
im = Image.open(self.image).convert('RGB')
im.save(img_io, format='WEBP')
name="this_is_my_webp_file.webp"
self.image = ContentFile(img_io.getvalue(), name)
super(Banner, self).save(*args, **kwargs) #Not at start anymore
Run Code Online (Sandbox Code Playgroud)