通过PyQt5使用base64将字节转换为图像

时间:2018-05-18 22:26:07

标签: python-3.x base64 pyqt5

我用base64

转换了这样的png文件
b'iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAAangAAGp4B8NQjJQAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAANRSURB\nVGiB7dpPqFVVFMfxz3tKVGS97EEGGYSZORGKJxHUw/4QgeNoVDTMAiuhoSAIgaD9/wMNhBo0qCZN\nghpIf0ZiDeRFFBJBEpFWgqG+euptsN957Hc853ruOeteL+IPFhzOvay1v/vss/beax+uaLw0Eezv\nGmzGpkWbKv1+AnM4jG9xJjh+J92CF/A15tFraPP4Cs9jzchbnelOfICzmje+zs7ifdwxSoDr8RoW\nAgDKtoB9WDVsiEfw2xAAynYUDw4LYhfOjQCisHPYGQkwgTdGCFC2VwVl13cvIURh73SFeGkMIAp7\nsS3EFjGp9TiexlrciifxRws/C3hgUIgbxGSnf3FPhf9N0qw+qL+jUvpvrDcDIHr4tE+MT1r6fKUp\nxAYxQ6onJYo6vd7S5wLWNQHZHwTRw/dYWRFjhbRwbOv3vYtBTEvjOgqkJ/V8DrMCezv6nMfqfiDb\ngyEKm8Nb0rvX5Unk9mw/kG+GBDIM+zJveD71r8Lfqsf0OOo/aXidYnmjN4uDOIID+FWak+7CY7gq\nyL9FXzPS5myZntPtUR+TcvzdNYE34OeOMcq2rSpQ27xe2DM1ALnuDQZZmhwnsyA3NWhIPz0hvWM9\n/ODCwgMcxO8d4+SaLi5ykOs6Ot2CGxevN0q9X6V/OsbJtbQlzkGiS0OnKu5N4ObAGEttzkEie+q8\nNLzKuk3KYlE6WVzkIH8FBpiT3peyZgNjwJ/FRQ7yU2CAz2rubw2MQdbmHOTHwACfV9ybxMOBMahp\n87UGK3nW2QnVK4T7AnzndgZXF87zJ3Iahxr2RD8dkDZmZT0a4DvXQanjsRwEPg4I8EXN/YcCfOf6\nqN+PERurmQq/k9ITjxpWF91Y0X2rO32hS9OBED0Ntrp0Lz5UlWtWSqvj4j/nta8jNy4+0K0cVJdi\n1+IpaXG5UftjicblILoV6A7rf74xJVX22/geuEBHt5LpL9KR2qw0DNbjcXyoXYWxGFIDl0wLXRZF\n7EIvjwHE7q4QpDX/vksIsUfwXmmH4RyA9nsntkcC5Jo1usPQ+4cFUeiyOJ7OtU46NmibTnM7jbdx\n+ygBypqSCsptP+HYprp0NJCG8VHNjFQiXS+tUIuZ+KRUFzgi7ey+M2Yf1VxRpP4H+dEoOtaum3IA\nAAAASUVORK5CYII=\n'

我有一个GUİ将此代码转换为图像并再次成像,但当我输入它并将其与.toPlainText()一起使用时,它什么都没有。

enter image description here

如果我手动输入脚本,它会起作用: enter image description here

如何定义变量来修复它?

1 个答案:

答案 0 :(得分:3)

问题是toPlainTex()返回的字符串实际上必须是bytearray,转换它的方法是使用ast.literal(),如下所示:

import ast

from PyQt5 import QtCore, QtGui, QtWidgets

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        lay = QtWidgets.QVBoxLayout(self)
        self.textEdit = QtWidgets.QTextEdit()
        self.label = QtWidgets.QLabel()
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        button = QtWidgets.QPushButton("convert")
        lay.addWidget(self.textEdit)
        lay.addWidget(button)
        lay.addWidget(self.label)
        button.clicked.connect(self.on_clicked)

    def on_clicked(self):
        text = self.textEdit.toPlainText()
        try:
            data = ast.literal_eval(text)
            ba = QtCore.QByteArray.fromBase64(data)
            pixmap = QtGui.QPixmap()
            if pixmap.loadFromData(ba, "PNG"):
                self.label.setPixmap(pixmap)
        except SyntaxError:
            pass

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

enter image description here

enter image description here