2424_float_types = []
2525
2626
27- def _array_to_b64str (img , backend = "pil" , compression = 4 ):
27+ def _array_to_b64str (img , backend = "pil" , compression = 4 , ext = "png" ):
2828 """Converts a numpy array of uint8 into a base64 png string.
2929
3030 Parameters
@@ -36,6 +36,8 @@ def _array_to_b64str(img, backend="pil", compression=4):
3636 otherwise pypng.
3737 compression: int, between 0 and 9
3838 compression level to be passed to the backend
39+ ext: str, 'png' or 'jpg'
40+ compression format used to generate b64 string
3941 """
4042 # PIL and pypng error messages are quite obscure so we catch invalid compression values
4143 if compression < 0 or compression > 9 :
@@ -52,6 +54,9 @@ def _array_to_b64str(img, backend="pil", compression=4):
5254 raise ValueError ("Invalid image shape" )
5355 if backend == "auto" :
5456 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+
5560 if backend == "pypng" :
5661 ndim = img .ndim
5762 sh = img .shape
@@ -72,9 +77,14 @@ def _array_to_b64str(img, backend="pil", compression=4):
7277 "install pillow or use `backend='pypng'."
7378 )
7479 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"
7686 with BytesIO () as stream :
77- pil_img .save (stream , format = "png" , compress_level = compression )
87+ pil_img .save (stream , format = ext , compress_level = compression )
7888 base64_string = prefix + base64 .b64encode (stream .getvalue ()).decode ("utf-8" )
7989 return base64_string
8090
@@ -135,6 +145,7 @@ def imshow(
135145 binary_string = None ,
136146 binary_backend = "auto" ,
137147 binary_compression_level = 4 ,
148+ binary_format = "png" ,
138149):
139150 """
140151 Display an image, i.e. data on a 2D regular raster.
@@ -239,6 +250,9 @@ def imshow(
239250 test `len(fig.data[0].source)` and to time the execution of `imshow` to
240251 tune the level of compression. 0 means no compression (not recommended).
241252
253+ binary_format: str, 'png' (default) or 'jpg'
254+ compression format used to generate b64 string
255+
242256 Returns
243257 -------
244258 fig : graph_objects.Figure containing the displayed image
@@ -410,6 +424,7 @@ def imshow(
410424 img_rescaled ,
411425 backend = binary_backend ,
412426 compression = binary_compression_level ,
427+ ext = binary_format ,
413428 )
414429 trace = go .Image (source = img_str )
415430 else :
0 commit comments