编码Base64 Django ImageField流

时间:2016-03-23 13:28:24

标签: python django django-forms pillow

我通过自己的表单收到了一张图片,我不想像往常一样在FileField中使用CharField作为Base64。这是我目前的设置:

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)输出为:

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

对于JPG来说是:

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

是否可以将接收到的图像编码为base64并将其从流中保存到数据库中并暂时将其保存在某处?

编辑:让它立即正常运作!

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

基本上就是一切!

1 个答案:

答案 0 :(得分:5)

是的,可以使用PIL轻松完成!

如何:

将图像保存在缓冲区中并在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())