Encode Base64 Django ImageField Stream

前端 未结 1 1351
悲&欢浪女
悲&欢浪女 2020-12-20 20:55

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:

<
相关标签:
1条回答
  • 2020-12-20 21:41

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

    How to :

    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())
    

    Or :

    with open("yourImage.ext", "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read())
    
    0 讨论(0)
提交回复
热议问题