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+selenium 点击单选框-radio的实现方法

例子:以百度文库中选择文档的类型为例 问题一:遍历点击所有文档类型的单选框 # coding=utf-8 from selenium import webdriver from t...

Python常用小技巧总结

本文实例总结了Python常用的小技巧。分享给大家供大家参考。具体分析如下: 1. 获取本地mac地址: import uuid mac = uuid.uuid1().hex[-12...

python 通过SSHTunnelForwarder隧道连接redis的方法

背景:我司Redis服务器使用的亚马逊服务,本地需要通过跳板机,然后才有权限访问Redis服务。 连接原理:使用SSHTunnelForwarder模块,通过本地22端口ssh到跳板机,...

win与linux系统中python requests 安装

在 windows 系统下,只需要输入命令 pip install requests ,即可安装。 在 linux 系统下,只需要输入命令 sudo  pip install...

Win10下python 2.7.13 安装配置方法图文教程

Win10下python 2.7.13 安装配置方法图文教程

本文记录了Windows10安装Python2.7的详细步骤,分享给大家。 一、下载软件 Python的官方地址 点击Downloads找到进行下载 点击进行下载、有18M左右 下...