编码Base64 Django ImageField流 [英] Encode Base64 Django ImageField Stream

查看:445
本文介绍了编码Base64 Django ImageField流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过表单收到一个图像,我不想像往常一样保存在FileField中,而是保存在CharField中作为Base64.这是我当前的设置:

I receive an Image through my form, which I not want to save as usual in a FileField but in a CharField as Base64. This is my current setup:

models.py

class Image(models.Model):
    company = models.ForeignKey(Company)

    img = models.TextField()

    img_id = models.CharField(blank=True, null=True, max_length=64)
    img_class = models.CharField(blank=True, null=True, max_length=64)

    created = models.DateField(auto_now_add=True, editable=False)

forms.py

class ImageForm(forms.Form):
    img = forms.ImageField()
    img_id = forms.CharField(required=False)
    img_class = forms.CharField(required=False)

views.py

class ImageUploadView(LoginRequiredMixin, FormView):
    form_class = ImageForm
    template_name = "upload.html"
    success_url = reverse_lazy("home")

    def form_valid(self, form):
        account = Account.objects.get(user=self.request.user)
        html = Html.objects.get(company=account.company)

        if self.request.user.is_authenticated():
            company = Company.objects.get(account=account)

            form_img = form.cleaned_data['img']

            print(form_img.__dict__.keys())
            print(form_img.image)

        return super(ImageUploadView, self).form_valid(form)

print(form_img.__dict__.keys())的输出是

['file', 'content_type_extra', 'image', 'charset', '_name', 'content_type', '_size', 'field_name']

,Png图像的print(form_img.image)输出为:

and the output of print(form_img.image) for an Png Image is:

<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=183x161 at 0x7F087B2E6B90>

对于JPG,是:

<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=400x400 at 0x7F087B16EC50>

是否可以将接收到的图像编码为base64并从流中将其保存到数据库中,而无需将其临时保存在某个地方?

Is it possible to encode the received image as base64 and save it into the database from stream and with out temporarily saving it somewhere?

现在可以正常工作!

b64_img = base64.b64encode(form_img.file.read())

那基本上就是一切!

推荐答案

是的,可以使用PIL轻松实现!

Yes it's possible to do it easily with PIL !

将图像保存在缓冲区中并在base64中进行编码.

Save image in the buffer and encode it in base64.

import base64
import cStringIO

img_buffer = cStringIO.StringIO()
image.save(img_buffer, format="imageFormatYouWant")
img_str = base64.b64encode(img_buffer.getvalue())

或:

with open("yourImage.ext", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

这篇关于编码Base64 Django ImageField流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆