注意
前往結尾下載完整的範例程式碼。
CanvasAgg 示範#
此範例示範如何直接使用 agg 後端建立影像,這對於希望完全控制程式碼,而無需使用 pyplot 介面來管理圖表、關閉圖表等的 Web 應用程式開發人員可能會很有用。
注意
為了建立沒有圖形前端的圖表,不必避免使用 pyplot 介面 - 只需將後端設定為 "Agg" 就足夠了。
在此範例中,我們示範如何將 agg 畫布的內容儲存到檔案,以及如何將其提取到 numpy 陣列,然後將其傳遞給 Pillow。後者功能允許例如在 cgi 腳本內部使用 Matplotlib,無需將圖表寫入磁碟,並以 Pillow 支援的任何格式寫入影像。
from PIL import Image
import numpy as np
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure
fig = Figure(figsize=(5, 4), dpi=100)
# A canvas must be manually attached to the figure (pyplot would automatically
# do it). This is done by instantiating the canvas with the figure as
# argument.
canvas = FigureCanvasAgg(fig)
# Do some plotting.
ax = fig.add_subplot()
ax.plot([1, 2, 3])
# Option 1: Save the figure to a file; can also be a file-like object (BytesIO,
# etc.).
fig.savefig("test.png")
# Option 2: Retrieve a memoryview on the renderer buffer, and convert it to a
# numpy array.
canvas.draw()
rgba = np.asarray(canvas.buffer_rgba())
# ... and pass it to PIL.
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()
參考資料
此範例中顯示了下列函式、方法、類別和模組的使用