Coverage for nilearn/reporting/utils.py: 54%
26 statements
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-16 12:32 +0200
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-16 12:32 +0200
1"""Utility functions for the reporting module."""
3import base64
4import io
5import urllib.parse
6from pathlib import Path
8TEMPLATE_ROOT_PATH = Path(__file__).parent / "data"
10CSS_PATH = TEMPLATE_ROOT_PATH / "css"
12JS_PATH = TEMPLATE_ROOT_PATH / "js"
14HTML_TEMPLATE_PATH = TEMPLATE_ROOT_PATH / "html"
16HTML_PARTIALS_PATH = HTML_TEMPLATE_PATH / "partials"
19def _figure_to_bytes(fig, format, **kwargs):
20 """Save figure as as certain format and return it as bytes.
22 If a matplotlib axes is passed, it gets the parent figure.
23 """
24 # TODO move this entire module in a place
25 # where it won't be imported if matplotlib is not around
26 from matplotlib import pyplot as plt
28 if not isinstance(fig, (plt.Figure)):
29 fig = fig.figure
30 with io.BytesIO() as io_buffer:
31 fig.savefig(
32 io_buffer,
33 format=format,
34 facecolor="white",
35 edgecolor="white",
36 **kwargs,
37 )
38 return io_buffer.getvalue()
41def _figure_to_svg_bytes(fig):
42 """Save figure as svg and return it as bytes."""
43 return _figure_to_bytes(fig, format="svg")
46def _figure_to_png_bytes(fig):
47 """Save figure as png and return it as bytes."""
48 return _figure_to_bytes(fig, format="png", bbox_inches="tight")
51def figure_to_svg_base64(fig):
52 """Save figure as svg and return it as 64 bytes."""
53 return base64.b64encode(_figure_to_svg_bytes(fig)).decode()
56def figure_to_png_base64(fig):
57 """Save figure as png and return it as 64 bytes."""
58 return base64.b64encode(_figure_to_png_bytes(fig)).decode()
61def figure_to_svg_quoted(fig):
62 """Save figure as svg and return it as quoted string."""
63 return urllib.parse.quote(_figure_to_svg_bytes(fig).decode("utf-8"))