gpt4 book ai didi

python - 从 BytesIO 将图像上传到 ImageField

转载 作者:行者123 更新时间:2023-11-30 23:08:30 27 4
gpt4 key购买 nike

我想直接在模型保存中上传生成的图像,而不必先将其保存到文件中。

型号:

avatar = models.ImageField(upload_to="img/", null=True, blank=True)

def save(self, *args, **kwargs):
from .generate_avatar import Avatar
self.avatar = Avatar.generate(128, self.display_name, "PNG")

这是我的generate_avatar 类。

def generate(cls, size, string, filetype="JPEG"):
"""
Generates a squared avatar with random background color.

:param size: size of the avatar, in pixels
:param string: string to be used to print text and seed the random
:param filetype: the file format of the image (i.e. JPEG, PNG)
"""
render_size = max(size, Avatar.MIN_RENDER_SIZE)
image = Image.new('RGB', (render_size, render_size),
cls._background_color(string))
draw = ImageDraw.Draw(image)
font = cls._font(render_size)
text = cls._text(string)
draw.text(cls._text_position(render_size, text, font),
text,
fill=cls.FONT_COLOR,
font=font)
stream = BytesIO()
image = image.resize((size, size), Image.ANTIALIAS)
image.save(stream, format=filetype, optimize=True)
return stream.seek(0)

但是,这不起作用,没有错误只是保存 0。为什么?

最佳答案

要在 django 中“模拟”文件上传,请查看 django 的 SimpleUploadedFile 并执行以下操作:

from django.core.files.uploadedfile import SimpleUploadedFile

def save(self, *args, **kwargs)
avatar = Avatar.generate(128, self.display_name, "PNG")
self.avatar = SimpleUploadedFile(avatar.name, avatar.read())

关于python - 从 BytesIO 将图像上传到 ImageField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31682467/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com