Skip to content
This repository was archived by the owner on Feb 10, 2025. It is now read-only.

Add format parameter (to support TIFF/JPG files) #52

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions dash_canvas/utils/io_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@
from io import BytesIO
import base64

_allowed_formats = {
"jpg",
"png",
"tiff",
}

def array_to_data_url(img, dtype=None):
def array_to_data_url(img, dtype=None, format="png"):
"""
Converts numpy array to data string, using Pillow.

Expand All @@ -14,6 +19,8 @@ def array_to_data_url(img, dtype=None):
==========

img : numpy array
dtype : numpy datatype
format : Optional str, one of "jpg", "png" (default), or "tiff"

Returns
=======
Expand All @@ -22,11 +29,13 @@ def array_to_data_url(img, dtype=None):
"""
if dtype is not None:
img = img.astype(dtype)
if not format in _allowed_formats:
format = "png"
pil_img = Image.fromarray(img)
buff = BytesIO()
pil_img.save(buff, format="png")
prefix = b'data:image/png;base64,'
image_string = (prefix + base64.b64encode(buff.getvalue())).decode("utf-8")
pil_img.save(buff, format=format)
prefix = 'data:image/' + format + ';base64,'
image_string = prefix + base64.b64encode(buff.getvalue()).decode("utf-8")
return image_string


Expand Down