pythonbase64animated-gif

Encoding gif to base64 without writing to disk python


I am able to encode a gif to base64 by saving the data first.

    imageio.mimsave(output_fn, [img_as_ubyte(frame) for frame in gif], fps=original_fps)

    with open(output_fn, "rb") as gif_file:
            detect_base64 = 'data:image/gif;base64,{}'.format(base64.b64encode(gif_file.read()).decode())

I need to find a way to encode the gif above in the form an array of images, with the corresponding fps into base64 without the need of saving it into output_fn first.


Solution

  • The general approach is to use a BytesIO as a replacement for an open file, i.e.

    gif_file = io.BytesIO()
    
    imageio.mimsave(gif_file, [img_as_ubyte(frame) for frame in gif], 'GIF', fps=original_fps)
    
    detect_base64 = 'data:image/gif;base64,{}'.format(base64.b64encode(gif_file.getvalue()).decode())