Created
March 5, 2020 17:31
-
-
Save ganeshkumartk/4fc83b2b38ce9d9073810a46853b0d46 to your computer and use it in GitHub Desktop.
Utilities for base64 conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Utilities | |
""" | |
import re | |
import base64 | |
import numpy as np | |
from PIL import Image | |
from io import BytesIO | |
def base64_to_pil(img_base64): | |
""" | |
Convert base64 image data to PIL image | |
""" | |
image_data = re.sub('^data:image/.+;base64,', '', img_base64) | |
pil_image = Image.open(BytesIO(base64.b64decode(image_data))) | |
return pil_image | |
def np_to_base64(img_np): | |
""" | |
Convert numpy image (RGB) to base64 string | |
""" | |
img = Image.fromarray(img_np.astype('uint8'), 'RGB') | |
buffered = BytesIO() | |
img.save(buffered, format="PNG") | |
return u"data:image/png;base64," + base64.b64encode(buffered.getvalue()).decode("ascii") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment