Search code examples
pythonpysideqimageqfileqdatastream

I want to view the original Image


enter image description here

I want to view the original Image file.

But all Images are converted into the spotted,corrupted image.

It seems that the previous image is not equal to the behind image.

Please change the image size in the QImage's constructor into your arbitrary sample image's size.

If I excute this code, I caught the corrupted Image. Why?

enter image description here

I tried to change Format.Format_ARGB32_Premultiplied into various patterns.

But all patterns didn't go well.

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()

Solution

  • When you convert and save data by bytes you are losing the information of the dimension. If your goal is to save the image information it is best to convert the PIL to QImage, and save this QImage in the file, then you can simply recover it as shown below:

    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_())