Convert a matplotlib image to a base64 png representation Parameters ---------- image : matplotlib image object The image to be converted. Returns ------- image_base64 : string The UTF8-encoded base64 string representation of the png image.
(image)
| 355 | |
| 356 | |
| 357 | def image_to_base64(image): |
| 358 | """ |
| 359 | Convert a matplotlib image to a base64 png representation |
| 360 | |
| 361 | Parameters |
| 362 | ---------- |
| 363 | image : matplotlib image object |
| 364 | The image to be converted. |
| 365 | |
| 366 | Returns |
| 367 | ------- |
| 368 | image_base64 : string |
| 369 | The UTF8-encoded base64 string representation of the png image. |
| 370 | """ |
| 371 | ax = image.axes |
| 372 | binary_buffer = io.BytesIO() |
| 373 | |
| 374 | # image is saved in axes coordinates: we need to temporarily |
| 375 | # set the correct limits to get the correct image |
| 376 | lim = ax.axis() |
| 377 | ax.axis(image.get_extent()) |
| 378 | image.write_png(binary_buffer) |
| 379 | ax.axis(lim) |
| 380 | |
| 381 | binary_buffer.seek(0) |
| 382 | return base64.b64encode(binary_buffer.read()).decode("utf-8") |