'How to encode a image in Python to Base64?

I have a RGB image in a numpy array of 3 dimensions.

I am currently using this

base64.b64encode(img).decode('utf-8')

But when I copy/paste the output to this website https://codebeautify.org/base64-to-image-converter

It does not convert the image back.

But If I use this code:

import base64
with open("my_image.jpg", "rb") as img_file:
    my_string = base64.b64encode(img_file.read())
my_string = my_string.decode('utf-8')

then it works. But my image is not saved in memory. And I don't want to save it, because it will decrease the speed of the program.



Solution 1:[1]

You can encode the RGB directly to jpg in memory and create a base64 encoding of this.

jpg_img = cv2.imencode('.jpg', img)
b64_string = base64.b64encode(jpg_img[1]).decode('utf-8')

Full example:

import cv2
import base64
img = cv2.imread('test_image.jpg')
jpg_img = cv2.imencode('.jpg', img)
b64_string = base64.b64encode(jpg_img[1]).decode('utf-8')

The base 64 string should be decodable with https://codebeautify.org/base64-to-image-converter

Solution 2:[2]

Try This Method :- RGB image base64 encode/decode

import cStringIO
import PIL.Image

def encode_img(img_fn):
    with open(img_fn, "rb") as f:
        data = f.read()
        return data.encode("base64")

def decode_img(img_base64):
    decode_str = img_base64.decode("base64")
    file_like = cStringIO.StringIO(decode_str)
    img = PIL.Image.open(file_like)
    # rgb_img[c, r] is the pixel values.
    rgb_img = img.convert("RGB")
    return rgb_img

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ma9