Search code examples
pythonopencvbase64

Why is base64encoded output different for the same image?


This function below reads an image and converts it into base64 image string

def getBase64Image(filePath):
    with open(filePath, "rb") as img_file:
        my_string = base64.b64encode(img_file.read())
        my_string = my_string.decode('utf-8')
    return my_string

However, the function below take image as array(loaded from OpenCV) and converts it into base64 image string

def convertToBase64(image):
    image.tobytes()
    my_string = base64.b64encode(image)
    my_string = my_string.decode('utf-8')
    return my_string

The output string from the first function differs from the string produced by the second function. Why is that?

Ideally, I want the second function to produce the same base64 string as the first function.

Please, can someone guide me on how I can achieve this?


Solution

  • You first function uses the PNG/JPG image data "as-is" and encodes it.

    Your second function uses RAW bytes from the RGB or grayscale representation of the image and encodes that. If you want to convert RAW RGB to an image, you may use cv2.imencode() which will ouput PNG or JPG or whatever you like.

    def convertToBase64(image):
        #image.tobytes() -- don't need this
        _, converted = cv2.imencode( '.png', image)  # here the magic happens
        my_string = base64.b64encode(converted)  # and here
        my_string = my_string.decode('utf-8')
        return my_string
    

    And yeah, just in case it's not clear. You DON'T have to save the encoded image anywhere, it's all happening in memory.