Image & Base64 | OpenCV vs Pillow | Python

This tutorial will show you how to read an image file into base64 format, and convert an image to base64 format (and from base64 to an image) in OpenCV (cv2) and Pillow (PIL).

Base64 is a format to represent binary data in text. This is widely used on the web and email to deliver data like images.

1. Read Image as Base64

import base64
with open("your_image.jpg", "rb") as f:
  base64_str = base64.b64encode(f.read())

2. Convert Between Pillow & Base64

import base64
from io import BytesIO
from PIL import Image

# Pillow to base64
def pil_to_base64(pil_img):
  img_buffer = BytesIO()
  pil_img.save(img_buffer, format='JPEG')
  byte_data = img_buffer.getvalue()
  base64_str = base64.b64encode(byte_data)
  return base64_str
 
# base64 to Pillow
def base64_to_pil(base64_str):
  pil_img = base64.b64decode(base64_str)
  pil_img = BytesIO(pil_img)
  pil_img = Image.open(pil_img)
  return pil_img

3. Convert Between OpenCV & Base64

import base64
import numpy as np
import cv2

# OpenCV to base64
def cv2_base64(cv2_img):
  base64_str = cv2.imencode('.jpg', cv2_img)[1].tostring()
  base64_str = base64.b64encode(base64_str)
  return base64_str

# base64 to OpenCV
def base64_cv2(base64_str):
  imgString = base64.b64decode(base64_str)
  nparr = np.fromstring(imgString, np.uint8)
  cv2_img= cv2.imdecode(nparr, cv2.IMREAD_COLOR)
  return cv2_img

Syntax

base64.standard_b64encode(s)

Parameters:

Returns:

base64.standard_b64decode(s)

Parameters:

Returns:

References

Avatar photo
Steins

Developer & AI Researcher. Write about AI, web dev/hack.