24
24
_float_types = []
25
25
26
26
27
- def _array_to_b64str (img , backend = "pil" , compression = 4 ):
27
+ def _array_to_b64str (img , backend = "pil" , compression = 4 , ext = "png" ):
28
28
"""Converts a numpy array of uint8 into a base64 png string.
29
29
30
30
Parameters
@@ -36,6 +36,8 @@ def _array_to_b64str(img, backend="pil", compression=4):
36
36
otherwise pypng.
37
37
compression: int, between 0 and 9
38
38
compression level to be passed to the backend
39
+ ext: str, 'png' or 'jpg'
40
+ compression format used to generate b64 string
39
41
"""
40
42
# PIL and pypng error messages are quite obscure so we catch invalid compression values
41
43
if compression < 0 or compression > 9 :
@@ -52,6 +54,9 @@ def _array_to_b64str(img, backend="pil", compression=4):
52
54
raise ValueError ("Invalid image shape" )
53
55
if backend == "auto" :
54
56
backend = "pil" if pil_imported else "pypng"
57
+ if ext != "png" and backend != "pil" :
58
+ raise ValueError ("jpg binary strings are only available with PIL backend" )
59
+
55
60
if backend == "pypng" :
56
61
ndim = img .ndim
57
62
sh = img .shape
@@ -72,9 +77,14 @@ def _array_to_b64str(img, backend="pil", compression=4):
72
77
"install pillow or use `backend='pypng'."
73
78
)
74
79
pil_img = Image .fromarray (img )
75
- prefix = "data:image/png;base64,"
80
+ if ext == "jpg" or ext == "jpeg" :
81
+ prefix = "data:image/jpeg;base64,"
82
+ ext = "jpeg"
83
+ else :
84
+ prefix = "data:image/png;base64,"
85
+ ext = "png"
76
86
with BytesIO () as stream :
77
- pil_img .save (stream , format = "png" , compress_level = compression )
87
+ pil_img .save (stream , format = ext , compress_level = compression )
78
88
base64_string = prefix + base64 .b64encode (stream .getvalue ()).decode ("utf-8" )
79
89
return base64_string
80
90
@@ -135,6 +145,7 @@ def imshow(
135
145
binary_string = None ,
136
146
binary_backend = "auto" ,
137
147
binary_compression_level = 4 ,
148
+ binary_format = "png" ,
138
149
):
139
150
"""
140
151
Display an image, i.e. data on a 2D regular raster.
@@ -239,6 +250,9 @@ def imshow(
239
250
test `len(fig.data[0].source)` and to time the execution of `imshow` to
240
251
tune the level of compression. 0 means no compression (not recommended).
241
252
253
+ binary_format: str, 'png' (default) or 'jpg'
254
+ compression format used to generate b64 string
255
+
242
256
Returns
243
257
-------
244
258
fig : graph_objects.Figure containing the displayed image
@@ -410,6 +424,7 @@ def imshow(
410
424
img_rescaled ,
411
425
backend = binary_backend ,
412
426
compression = binary_compression_level ,
427
+ ext = binary_format ,
413
428
)
414
429
trace = go .Image (source = img_str )
415
430
else :
0 commit comments