matplotlib.pyplot画图 图片的二进制流的获取方法

yipeiwu_com6年前Python基础

有些时候,我们需要画图后的二进制数据流,matplotlib没有提供相关的api,通过源码查看与百度,得到下面此方法

import matplotlib.pyplot as plt
import numpy as np
import io
x=np.arange(10)
y=x
#plt.plot(x,y)
#canvas = plt.get_current_fig_manager().canvas
#canvas.draw()
fig=plt.figure()
plt.plot(x,y)
canvas=fig.canvas
#上面这段代码和上面注释掉的代码效果一样

#方法1
buffer = io.BytesIO()
canvas.print_png(buffer)
data=buffer.getvalue()
buffer.close()
#方法2
buf, size = canvas.print_to_buffer()
image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
buffer=io.BytesIO()
image.save(buffer,'PNG')
data=buffer.getvalue()
buffer.close()

with open('hhh.png',mode='wb') as f:
f.write(data)
#f=open('hh.png',mode='wb')
#f.write(data)
#f.close()

如果我们想把二进制的图片转成数组也是可以的,

buffer=io.BytesIO()
buffer.write(data)
img=Image.open(buffer)
img = np.asarray(img)

以上这篇matplotlib.pyplot画图 图片的二进制流的获取方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python 接口返回的json字符串实例

如下所示: JSON 函数 使用 JSON 函数需要导入 json 库:import json。 函数 描述 json.dumps 将 Python 对象编码成 JSON 字符串...

Python日期时间模块datetime详解与Python 日期时间的比较,计算实例代码

python中的datetime模块提供了操作日期和时间功能,该模块提供了五种核心对象:datetime时间日期类型,date日期类型,time时间类型,tzinfo时区类型,timed...

恢复百度云盘本地误删的文件脚本(简单方法)

今天被同步盘搞得焦头烂额。 辛苦码的代码(除了重要的、备份过的)都被删掉了…… 当时我就石化了。。。 随后发现同步盘目录有个delete目录,里面还有manifest.xml,和一堆改了...

pandas全表查询定位某个值所在行列的方法

如下所示: # create a dataframe with an integer feature and a categorical string feature demo_df...

使用python接入微信聊天机器人

本文实例为大家分享了python接入微信聊天机器人的具体代码,供大家参考,具体内容如下 1.安装库wxpy: pip install -U wxpy or pip instal...