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

Skip to content

Figure.export() #531

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jun 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/source/api/layouts/figure.rst
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ Methods
Figure.add_animations
Figure.clear
Figure.close
Figure.export
Figure.remove_animation
Figure.render
Figure.show
Expand Down
47 changes: 47 additions & 0 deletions fastplotlib/layouts/_figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ def __init__(

# if controller instances have been specified for each subplot
if controllers is not None:

# one controller for all subplots
if isinstance(controllers, pygfx.Controller):
controllers = [controllers] * len(self)
Expand Down Expand Up @@ -579,6 +580,52 @@ def clear(self):
for subplot in self:
subplot.clear()

def export(self, uri: str | Path | bytes, **kwargs):
"""
Use ``imageio`` for writing the current Figure to a file, or return a byte string.
Must have ``imageio`` installed.

Parameters
----------
uri: str | Path | bytes

kwargs: passed to imageio.v3.imwrite, see: https://imageio.readthedocs.io/en/stable/_autosummary/imageio.v3.imwrite.html

Returns
-------
None | bytes
see https://imageio.readthedocs.io/en/stable/_autosummary/imageio.v3.imwrite.html
"""
try:
import imageio.v3 as iio
except ModuleNotFoundError:
raise ImportError(
"imageio is required to use Figure.export(). Install it using pip or conda:\n"
"pip install imageio\n"
"conda install -c conda-forge imageio\n"
)
else:
snapshot = self.renderer.snapshot()
remove_alpha = True

# image formats that support alpha channel:
# https://en.wikipedia.org/wiki/Alpha_compositing#Image_formats_supporting_alpha_channels
alpha_support = [".png", ".exr", ".tiff", ".tif", ".gif", ".jxl", ".svg"]

if isinstance(uri, str):
if any([uri.endswith(ext) for ext in alpha_support]):
remove_alpha = False

elif isinstance(uri, Path):
if uri.suffix in alpha_support:
remove_alpha = False

if remove_alpha:
# remove alpha channel if it's not supported
snapshot = snapshot[..., :-1].shape

return iio.imwrite(uri, snapshot, **kwargs)

def _get_iterator(self):
return product(range(self.shape[0]), range(self.shape[1]))

Expand Down
Loading