gpt4 book ai didi

c# - Matplotlib savefig to BytesIO 是不是有点不对?

转载 作者:太空宇宙 更新时间:2023-11-03 13:54:52 25 4
gpt4 key购买 nike

我正在尝试保存 数字到内存流,与 SO 上的另一个示例完全相同:

import matplotlib.pyplot as plt
import io


plt.figure()
plt.plot([1, 2])
plt.title("test")
buf = io.BytesIO()
plt.savefig(buf, format = 'png')
plt.savefig("real.png", format = 'png')
buf.seek(0)
data = buf.read()
buf.close()
f = open('copy.png', 'w')
f.write(data)
f.close()

我发现 copy.png 的尺寸稍大,应用程序拒绝打开它。这是某种编码问题吗?

背景:

我正在尝试使用 python.net 通过 matplotlib 渲染图形并将它们传递给 C# 进行绘图。我想避免将图像写入磁盘。理想情况下,我想写入某种可以在 C# 中使用的字节数组。

最佳答案

尝试以二进制模式打开文件。

f = open('copy.png', 'wb')

来自文档:

Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files.

关于c# - Matplotlib savefig to BytesIO 是不是有点不对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12577110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com