File tree Expand file tree Collapse file tree 1 file changed +12
-8
lines changed Expand file tree Collapse file tree 1 file changed +12
-8
lines changed Original file line number Diff line number Diff line change 14
14
the backend to "Agg" would be sufficient.
15
15
16
16
In this example, we show how to save the contents of the agg canvas to a file,
17
- and how to extract them to a string, which can in turn be passed off to PIL or
18
- put in a numpy array. The latter functionality allows e.g. to use Matplotlib
19
- inside a cgi-script *without* needing to write a figure to disk.
17
+ and how to extract them to a numpy array, which can in turn be passed off
18
+ to Pillow_. The latter functionality allows e.g. to use Matplotlib inside a
19
+ cgi-script *without* needing to write a figure to disk, and to write images in
20
+ any format supported by Pillow.
21
+
22
+ .. _Pillow: https://pillow.readthedocs.io/
20
23
"""
21
24
22
25
from matplotlib .backends .backend_agg import FigureCanvasAgg
39
42
# etc.).
40
43
fig .savefig ("test.png" )
41
44
42
- # Option 2: Retrieve a view on the renderer buffer...
45
+ # Option 2: Retrieve a memoryview on the renderer buffer, and convert it to a
46
+ # numpy array.
43
47
canvas .draw ()
44
- buf = canvas .buffer_rgba ()
45
- # ... convert to a NumPy array ...
46
- X = np .asarray (buf )
48
+ rgba = np .asarray (canvas .buffer_rgba ())
47
49
# ... and pass it to PIL.
48
- im = Image .fromarray (X )
50
+ im = Image .fromarray (rgba )
51
+ # This image can then be saved to any format supported by Pillow, e.g.:
52
+ im .save ("test.bmp" )
49
53
50
54
# Uncomment this line to display the image using ImageMagick's `display` tool.
51
55
# im.show()
You can’t perform that action at this time.
0 commit comments