2012-11-09 62 views
0

我嘗試POST POST QPixmap圖像bia http。要做到這一點,我必須讓QPixmap保存到臨時文件並將其作爲python文件類讀取,請執行POST。但我認爲還有另一種方式來發布QPixmap。猜猜看,QPixmap保存到StringIO(或其他),並與我可以做POST。pyqt:QPixmap保存到StringIO?

目前我寫這樣。

from poster.encode import multipart_encode 
from poster.streaminghttp import register_openers 
import urllib2, os 

tmpIm = "c:/tmpIm.png" 
PIXMAP.save(tmpIm, "PNG") 
register_openers() 
_f = open(tmpIm, "rb") 
datagen, headers = multipart_encode({"image": _f}) 
request = urllib2.Request(UPLOAD_URL, datagen, headers) 
_rnt = urllib2.urlopen(request) 
_f.close() 
os.remove(tmpIm) 

回答

2

您可以通過QBuffer保存QPixmapQByteArray,然後讀取到一個StringIO對象:

from PyQt4.QtCore import QBuffer, QByteArray, QIODevice 
from PyQt4.QtGui import QPixmap, QApplication 

import cStringIO as StringIO 


if __name__ == '__main__': 
    # Create a QApplication so that QPixmaps will work. 
    app = QApplication([]) 

    # Load a PNG into a QPixmap. 
    pixmap = QPixmap('c:/in.png') 

    # Save QPixmap to QByteArray via QBuffer. 
    byte_array = QByteArray() 
    buffer = QBuffer(byte_array) 
    buffer.open(QIODevice.WriteOnly) 
    pixmap.save(buffer, 'PNG') 

    # Read QByteArray containing PNG into a StringIO. 
    string_io = StringIO.StringIO(byte_array) 
    string_io.seek(0) 

    # Write the StringIO back to a file to test all is ok. 
    with open('c:/out.png', 'wb') as out_file: 
     out_file.write(string_io.read())