Categories
不学无术 木有技术

matplotlib 存储到内存文件 save to memory file(buffer) instead of disk file / PyQt4

References:
http://stackoverflow.com/questions/4330812/how-do-i-clear-a-stringio-object
http://stackoverflow.com/questions/8598673/how-to-save-a-pylab-figure-into-in-memory-file-which-can-be-read-into-pil-image
 
In fact Python have a StringIO module to deal with this problem, it works pretty fine with PyQt and matplotlib.
Procedures:
1. [SAVE] Create a StringIO object (or cStringIO which have faster speed)
2. [SAVE] Call savefig method of matplotlib and use the StringIO object instead as the input variable
3. [LOAD] Use QImage to read from StringIO object (via fromData method)
4. [LOAD] Use QPixmap and blabla to show the image….
 
Code:
 

# StringIO with matplotlib test
import matplotlib.pyplot as plt
import cStringIO
from PyQt4 import QtCore, QtGui
import sys
import cPickle
fig = plt.figure()
plt.plot([1, 2])
buf = cStringIO.StringIO()
plt.savefig(buf, format='png')
buf.seek(0)
app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()
widget.resize(250, 150)
widget.setWindowTitle('simple')
qimg = QtGui.QImage.fromData(buf.getvalue())
pixmap = QtGui.QPixmap.fromImage(qimg)
label = QtGui.QLabel(widget)
label.setPixmap(pixmap)
label.setGeometry(0, 0, 250, 150)
widget.show()
sys.exit(app.exec_())