Is it possible to create encoded base64 URL from Image object?

前端 未结 4 1061
陌清茗
陌清茗 2020-11-30 09:21

I am looking to create base64 inline encoded data of images for display in a table using canvases. Python generates and creates the web page dynamically. As it stands python

4条回答
  •  借酒劲吻你
    2020-11-30 09:36

    I use PNG when I save to the buffer. With JPEG the numpy arrays are a bit different.

    import base64
    import io
    
    import numpy as np
    from PIL import Image
    
    image_path = 'dog.jpg'
    
    img2 = np.array(Image.open(image_path))
    
    # Numpy -> b64
    buffered = io.BytesIO()
    Image.fromarray(img2).save(buffered, format="PNG")
    b64image = base64.b64encode(buffered.getvalue())
    
    # b64 -> Numpy
    img = np.array(Image.open(io.BytesIO(base64.b64decode(b64image))))
    
    print(img.shape)
    np.testing.assert_almost_equal(img, img2)
    

    Note that it will be slower.

提交回复
热议问题