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正则表达式匹配日期与时间的方法

下面给大家介绍下Python正则表达式匹配日期与时间 #!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Ran...

Python去除字符串两端空格的方法

目的   获得一个首尾不含多余空格的字符串 方法 可以使用字符串的以下方法处理: string.lstrip(s[, chars]) Return a copy of the stri...

Python使用pyshp库读取shapefile信息的方法

通过pyshp库,可以读写Shapefile文件,查询相关信息,github地址为 https://github.com/GeospatialPython/pyshp import...

深入理解python中sort()与sorted()的区别

Python list内置sort()方法用来排序,也可以用python内置的全局sorted()方法来对可迭代的序列排序生成新的序列 一,最简单的排序 1.使用sort排序 my_...

Python基础学习之类与实例基本用法与注意事项详解

本文实例讲述了Python基础学习之类与实例基本用法与注意事项。分享给大家供大家参考,具体如下: 前言 和其他编程语言相比,Python用非常少的新语法和语义将类加入到语言中。Pytho...