编码Base64 Django ImageField流

yth*_*tho 5 python django django-forms pillow

我通过表单收到一个图像,我不想像往常一样保存在a中,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)
Run Code Online (Sandbox Code Playgroud)

表格

class ImageForm(forms.Form):
    img = forms.ImageField()
    img_id = forms.CharField(required=False)
    img_class = forms.CharField(required=False)
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

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

['file', 'content_type_extra', 'image', 'charset', '_name', 'content_type', '_size', 'field_name']
Run Code Online (Sandbox Code Playgroud)

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

<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=183x161 at 0x7F087B2E6B90>
Run Code Online (Sandbox Code Playgroud)

对于JPG,它是:

<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=400x400 at 0x7F087B16EC50>
Run Code Online (Sandbox Code Playgroud)

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

编辑:现在就可以工作了!

b64_img = base64.b64encode(form_img.file.read())
Run Code Online (Sandbox Code Playgroud)

基本上就是一切!

1ro*_*mat 5

是的,使用PIL可以轻松做到这一点!

如何 :

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

import base64
import cStringIO

img_buffer = cStringIO.StringIO()
image.save(img_buffer, format="imageFormatYouWant")
img_str = base64.b64encode(img_buffer.getvalue())
Run Code Online (Sandbox Code Playgroud)

要么 :

with open("yourImage.ext", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())
Run Code Online (Sandbox Code Playgroud)