8000 Small improvements to canvasagg example. by anntzer · Pull Request #20376 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

Small improvements to canvasagg example. #20376

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 1 commit into from
Jun 7, 2021
Merged
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
20 changes: 12 additions & 8 deletions examples/user_interfaces/canvasagg.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,12 @@
the backend to "Agg" would be sufficient.

In this example, we show how to save the contents of the agg canvas to a file,
and how to extract them to a string, which can in turn be passed off to PIL or
put in a numpy array. The latter functionality allows e.g. to use Matplotlib
inside a cgi-script *without* needing to write a figure to disk.
and how to extract them to a numpy array, which can in turn be passed off
to Pillow_. The latter functionality allows e.g. to use Matplotlib inside a
cgi-script *without* needing to write a figure to disk, and to write images in
any format supported by Pillow.

.. _Pillow: https://pillow.readthedocs.io/
"""

from matplotlib.backends.backend_agg import FigureCanvasAgg
Expand All @@ -39,13 +42,14 @@
# etc.).
fig.savefig("test.png")

# Option 2: Retrieve a view on the renderer buffer...
# Option 2: Retrieve a memoryview on the renderer buffer, and convert it to a
# numpy array.
canvas.draw()
buf = canvas.buffer_rgba()
# ... convert to a NumPy array ...
X = np.asarray(buf)
rgba = np.asarray(canvas.buffer_rgba())
# ... and pass it to PIL.
im = Image.fromarray(X)
im = Image.fromarray(rgba)
# This image can then be saved to any format supported by Pillow, e.g.:
im.save("test.bmp")

# Uncomment this line to display the image using ImageMagick's `display` tool.
# im.show()
Expand Down
0