Skip to content

Instantly share code, notes, and snippets.

@patharanordev
Last active August 15, 2023 01:17
Show Gist options
  • Save patharanordev/e22f2fe1c2593c9e5d9f7fbd00d8da09 to your computer and use it in GitHub Desktop.
Save patharanordev/e22f2fe1c2593c9e5d9f7fbd00d8da09 to your computer and use it in GitHub Desktop.
Convert image from cv2.imread to img.src in HTML

Encode image in nparray to base64

Encode base64 function:

import cv2
import base64

def encode_img(img, im_type):
    """Encodes an image as a png and encodes to base 64 for display."""
    success, encoded_img = cv2.imencode('.{}'.format(im_type), img)
    if success:
        return base64.b64encode(encoded_img).decode()
    return ''

Usage

Assume input file is jpg file format :

img = cv2.imread(file_path)
encoded_img = encode_img(img, 'jpg')
b64_src = 'data:image/jpeg;base64,'
img_src = b64_src + encoded_img
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment