我要查看原图

I want to view the original Image

我想查看原始图像文件。

但是所有图像都被转换成斑点、损坏的图像。

好像前图和后图不一样

请将 QImage 的构造函数中的图像大小更改为您的任意示例图像的大小。

如果我执行这段代码,我会捕获到损坏的图像。为什么?

我尝试将格式更改。Format_ARGB32_Premultiplied 为各种模式。

但并不是所有的模式都很顺利。

from PIL import Image
import numpy as np
from PySide import QtCore
from PySide import QtGui
import sys
#the original file
filename = 'Any_Data.png'

im = Image.open(filename)
data = np.array(im)

file_ = QtCore.QFile("test_file.img")
file_.open(QtCore.QIODevice.WriteOnly)
qdatastream = QtCore.QDataStream(file_)


bytedatas = QtCore.QByteArray(data.tobytes())
#print(bytedatas)
#print(len(data.tobytes()),type(data))

qdatastream << bytedatas

output_file_ = QtCore.QFile("test_file.img")
output_file_.open(QtCore.QIODevice.ReadOnly)
qdatastream = QtCore.QDataStream(output_file_)
#the behind file
bytedata = QtCore.QByteArray()

qdatastream >> bytedata


Image = QtGui.QImage(220,133,QtGui.QImage.Format.Format_ARGB32_Premultiplied)
Image.fromData(bytedata)
def main():
    try:
        QtGui.QApplication([])
    except Exception as e:
        print(e)

    widget = QtGui.QLabel()

    pixmap = QtGui.QPixmap()
    pixmap.convertFromImage(Image)
    widget.setPixmap(pixmap)

    widget.show()
    sys.exit(QtGui.QApplication.exec_())
if __name__ == "__main__":
    main()

当您按字节转换和保存数据时,您会丢失维度信息。如果你的目标是保存图像信息最好将PIL转换为QImage,并将这个QImage保存在文件中,那么你可以简单地恢复它,如下所示:

import sys

from PIL import Image
import numpy as np

from PySide import QtCore, QtGui

filename = 'Any_Data.png'
filename_out = "data.bin"

im = Image.open(filename)
data = np.array(im)
qimagein = QtGui.QImage(data.data, data.shape[1], data.shape[0], data.strides[0], QtGui.QImage.Format_RGB888)

# save data
filewrite = QtCore.QFile(filename_out)
filewrite.open(QtCore.QIODevice.WriteOnly)
out_datastream = QtCore.QDataStream(filewrite)
out_datastream << qimagein

# read data
fileread = QtCore.QFile(filename_out)
fileread.open(QtCore.QIODevice.ReadOnly)
qimageout = QtGui.QImage()
in_datastream = QtCore.QDataStream(fileread)
in_datastream >> qimageout

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    w = QtGui.QLabel()
    pix = QtGui.QPixmap.fromImage(qimageout)
    w.setPixmap(pix)
    w.show()
    sys.exit(app.exec_())