QPixmap 宽度和高度 return 0

QPixmap width and height return 0

问题图片

环境

降序

使用以下代码,其中image_path是问题图片的绝对路径。(这不是找不到图片的问题)

pixmapHight和pixmapWidth会取0,但是用默认APP可以很好的打开和查看图片

对于大多数图片,这段代码都运行良好,但在这个特殊的图片上却失败了。

所以谁能解释一下并给我一些建议?

pixmap = QPixmap(image_path)
pixmapHight = pixmap.height()
pixmapWidth = pixmap.width()

PSthis question好像是一样的,但是答案不被接受,我的问题也不被接受。

我发现是后缀错误导致的。

本地保存的图片后缀为.png,实际格式为jpg。

当指定正确的格式时,例如:QPixmap(image_path, format = 'jpg'),我可以得到正确的高度和宽度。

这是我检查真实格式的示例代码:

import os
import sys
import imghdr
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class DemoApp(QMainWindow):
    def is_type_wrong(self, path):
    current_type = path[path.rfind('.')+1:]
    real_type = 'xxx'
    if path.lower().endswith('.gif') or path.lower().endswith('.jpg') or path.lower().endswith('.png'):
        header = []
        with open(path, 'rb') as f:
            while(len(header) < 5):
                header.append(f.read(1))
        print(header)
        if (header[0] == b'\x47' and header[1] and b'\x49' and header[2] == b'\x46' and header[3] == b'\x38'):
            real_type = 'gif'
        if (header[0] == b'\xff' and header[1] == b'\xd8'):
            real_type = 'jpg'
        if (header[0] == b'\x89' and header[1] == b'\x50' and header[2] == b'\x4e' and header[3] == b'\x47' and header[4] == b'\x0D'):
            real_type = 'png'
    return current_type != real_type, real_type

def __init__(self, parent=None):
    super(DemoApp, self).__init__(parent)
    image_path_list = ['D:\FailPic.png', 'D:\OkPic.png', 'D:\FromWeb.jpg']
    for image_path in image_path_list:
        if os.path.exists(image_path):
            fmt = imghdr.what(image_path)
            if fmt == None:
                # I get one picture still can be opened with default app while imghdr.what return None
                isWrongType, real_type = self.is_type_wrong(image_path)
                if isWrongType:
                    fmt = real_type
                else:
                    print("!!! corrupted picture: %s" %image_path)
            pixmap = QPixmap(image_path, format = fmt)
            pixmapHight = pixmap.height()
            pixmapWidth = pixmap.width()
            print("[%s]isNull:%d pixmapHight: %f, pixmapWidth: %f, fmt: %s" %(image_path, pixmap.isNull(), pixmapHight, pixmapWidth, fmt))
        else:
            print("pic % not found" %(image_path))
if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_window = DemoApp()
    main_window.show()
    sys.exit(app.exec_())