如何将 matplotlib plt.savefig() 保存到 io.BytesIO 缓冲区

你可以将 io.BytesIO() 作为第一个参数传递给 plt.savefig()。注意 format 默认为 "png",但最佳做法是显式指定它。

savefig_bytesio.py
# Save plot to BytesIO
bio = io.BytesIO()
plt.savefig(bio, dpi=250, format="png")

完整示例:

savefig_bytesio.py
#!/usr/bin/env python3
import numpy as np
import io
import matplotlib.pyplot as plt

# Generate data
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)

# Plot data
plt.plot(x, y)

# Save plot to BytesIO
bio = io.BytesIO()
plt.savefig(bio, dpi=250, format="png")

# Cleanup plot
plt.close(plt.gcf())
plt.clf()

# Write BytesIO to file
with open("plot.png", "wb") as f:
    f.write(bio.getvalue())

输出 plot.png

Sine wave plot saved to BytesIO buffer and written to PNG file using matplotlib


Check out similar posts by category: Python