10
10
pil_imported = False
11
11
12
12
13
- def image_array_to_data_uri (img , backend = "pil" , compression = 4 , ext = "png" ):
13
+ def image_array_to_data_uri (
14
+ img , backend = "pil" , compression = 4 , ext = "webp" , backend_kwargs = None
15
+ ):
14
16
"""Converts a numpy array of uint8 into a base64 png or jpg string.
15
17
16
18
Parameters
@@ -22,8 +24,10 @@ def image_array_to_data_uri(img, backend="pil", compression=4, ext="png"):
22
24
otherwise pypng.
23
25
compression: int, between 0 and 9
24
26
compression level to be passed to the backend
25
- ext: str, 'png' or 'jpg'
27
+ ext: str, 'webp', ' png', or 'jpg'
26
28
compression format used to generate b64 string
29
+ backend_kwargs : dict or None
30
+ keyword arguments to be passed to the backend
27
31
"""
28
32
# PIL and pypng error messages are quite obscure so we catch invalid compression values
29
33
if compression < 0 or compression > 9 :
@@ -41,15 +45,25 @@ def image_array_to_data_uri(img, backend="pil", compression=4, ext="png"):
41
45
if backend == "auto" :
42
46
backend = "pil" if pil_imported else "pypng"
43
47
if ext != "png" and backend != "pil" :
44
- raise ValueError ("jpg binary strings are only available with PIL backend" )
48
+ raise ValueError (
49
+ "webp and jpg binary strings are only available with PIL backend"
50
+ )
51
+
52
+ if backend_kwargs is None :
53
+ backend_kwargs = {}
45
54
46
55
if backend == "pypng" :
47
56
ndim = img .ndim
48
57
sh = img .shape
49
58
if ndim == 3 :
50
59
img = img .reshape ((sh [0 ], sh [1 ] * sh [2 ]))
51
60
w = Writer (
52
- sh [1 ], sh [0 ], greyscale = (ndim == 2 ), alpha = alpha , compression = compression
61
+ sh [1 ],
62
+ sh [0 ],
63
+ greyscale = (ndim == 2 ),
64
+ alpha = alpha ,
65
+ compression = compression ,
66
+ ** backend_kwargs
53
67
)
54
68
img_png = from_array (img , mode = mode )
55
69
prefix = "data:image/png;base64,"
@@ -63,13 +77,22 @@ def image_array_to_data_uri(img, backend="pil", compression=4, ext="png"):
63
77
"install pillow or use `backend='pypng'."
64
78
)
65
79
pil_img = Image .fromarray (img )
66
- if ext == "jpg" or ext == "jpeg" :
80
+ if ext == "webp" :
81
+ prefix = "data:image/webp;base64,"
82
+ ext = "webp"
83
+ elif ext == "jpg" or ext == "jpeg" :
67
84
prefix = "data:image/jpeg;base64,"
68
85
ext = "jpeg"
69
86
else :
70
87
prefix = "data:image/png;base64,"
71
88
ext = "png"
72
89
with BytesIO () as stream :
73
- pil_img .save (stream , format = ext , compress_level = compression )
90
+ pil_img .save (
91
+ stream ,
92
+ format = ext ,
93
+ compress_level = compression ,
94
+ lossless = True ,
95
+ ** backend_kwargs
96
+ )
74
97
base64_string = prefix + base64 .b64encode (stream .getvalue ()).decode ("utf-8" )
75
98
return base64_string
0 commit comments