From 3124bdaf714a3e2e0b8ba98a87f75c56463834c6 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Mon, 7 Jun 2021 07:17:40 +0200 Subject: [PATCH] Small improvements to canvasagg example. In particular, show how Pillow can be used to save images in formats not directly supported by Matplotlib. Also directly convert the buffer to an array (with only brief, in-passing mention of memoryviews), as memoryviews are rather technical. --- examples/user_interfaces/canvasagg.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/examples/user_interfaces/canvasagg.py b/examples/user_interfaces/canvasagg.py index 0ee163833a3b..60b0e320db6e 100644 --- a/examples/user_interfaces/canvasagg.py +++ b/examples/user_interfaces/canvasagg.py @@ -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 @@ -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()