Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a8bc4ee

Browse files
authored
Figure.export() (#531)
1 parent 3f5cf9d commit a8bc4ee

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

docs/source/api/layouts/figure.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ Methods
3737
Figure.add_animations
3838
Figure.clear
3939
Figure.close
40+
Figure.export
4041
Figure.remove_animation
4142
Figure.render
4243
Figure.show

fastplotlib/layouts/_figure.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ def __init__(
128128

129129
# if controller instances have been specified for each subplot
130130
if controllers is not None:
131+
131132
# one controller for all subplots
132133
if isinstance(controllers, pygfx.Controller):
133134
controllers = [controllers] * len(self)
@@ -579,6 +580,52 @@ def clear(self):
579580
for subplot in self:
580581
subplot.clear()
581582

583+
def export(self, uri: str | Path | bytes, **kwargs):
584+
"""
585+
Use ``imageio`` for writing the current Figure to a file, or return a byte string.
586+
Must have ``imageio`` installed.
587+
588+
Parameters
589+
----------
590+
uri: str | Path | bytes
591+
592+
kwargs: passed to imageio.v3.imwrite, see: https://imageio.readthedocs.io/en/stable/_autosummary/imageio.v3.imwrite.html
593+
594+
Returns
595+
-------
596+
None | bytes
597+
see https://imageio.readthedocs.io/en/stable/_autosummary/imageio.v3.imwrite.html
598+
"""
599+
try:
600+
import imageio.v3 as iio
601+
except ModuleNotFoundError:
602+
raise ImportError(
603+
"imageio is required to use Figure.export(). Install it using pip or conda:\n"
604+
"pip install imageio\n"
605+
"conda install -c conda-forge imageio\n"
606+
)
607+
else:
608+
snapshot = self.renderer.snapshot()
609+
remove_alpha = True
610+
611+
# image formats that support alpha channel:
612+
# https://en.wikipedia.org/wiki/Alpha_compositing#Image_formats_supporting_alpha_channels
613+
alpha_support = [".png", ".exr", ".tiff", ".tif", ".gif", ".jxl", ".svg"]
614+
615+
if isinstance(uri, str):
616+
if any([uri.endswith(ext) for ext in alpha_support]):
617+
remove_alpha = False
618+
619+
elif isinstance(uri, Path):
620+
if uri.suffix in alpha_support:
621+
remove_alpha = False
622+
623+
if remove_alpha:
624+
# remove alpha channel if it's not supported
625+
snapshot = snapshot[..., :-1].shape
626+
627+
return iio.imwrite(uri, snapshot, **kwargs)
628+
582629
def _get_iterator(self):
583630
return product(range(self.shape[0]), range(self.shape[1]))
584631

0 commit comments

Comments
 (0)