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

Skip to content

Commit 028a58b

Browse files
authored
Merge pull request #14923 from anntzer/unprinttobuf
In examples, prefer buffer_rgba to print_to_buffer.
2 parents 3fb246c + 86fbce7 commit 028a58b

File tree

2 files changed

+10
-15
lines changed

2 files changed

+10
-15
lines changed

examples/misc/agg_buffer.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
Agg Buffer
44
==========
55
6-
Use backend agg to access the figure canvas as an RGB string and then
7-
convert it to an array and pass it to Pillow for rendering.
6+
Use backend agg to access the figure canvas as an RGBA buffer, convert it to an
7+
array, and pass it to Pillow for rendering.
88
"""
99

1010
import numpy as np
@@ -18,14 +18,11 @@
1818

1919
agg = canvas.switch_backends(FigureCanvasAgg)
2020
agg.draw()
21-
s, (width, height) = agg.print_to_buffer()
22-
23-
# Convert to a NumPy array.
24-
X = np.frombuffer(s, np.uint8).reshape((height, width, 4))
21+
X = np.asarray(agg.buffer_rgba())
2522

2623
# Pass off to PIL.
2724
from PIL import Image
28-
im = Image.frombytes("RGBA", (width, height), s)
25+
im = Image.fromarray(X)
2926

3027
# Uncomment this line to display the image using ImageMagick's `display` tool.
3128
# im.show()

examples/user_interfaces/canvasagg.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,16 +37,14 @@
3737
# etc.).
3838
fig.savefig("test.png")
3939

40-
# Option 2: Save the figure to a string.
40+
# Option 2: Retrieve a view on the renderer buffer...
4141
canvas.draw()
42-
s, (width, height) = canvas.print_to_buffer()
43-
44-
# Option 2a: Convert to a NumPy array.
45-
X = np.frombuffer(s, np.uint8).reshape((height, width, 4))
46-
47-
# Option 2b: Pass off to PIL.
42+
buf = canvas.buffer_rgba()
43+
# ... convert to a NumPy array ...
44+
X = np.asarray(buf)
45+
# ... and pass it to PIL.
4846
from PIL import Image
49-
im = Image.frombytes("RGBA", (width, height), s)
47+
im = Image.fromarray(X)
5048

5149
# Uncomment this line to display the image using ImageMagick's `display` tool.
5250
# im.show()

0 commit comments

Comments
 (0)