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()