python - 如何在PyQt5中捕获libpng错误错误的自适应滤波器

标签 python error-handling pyqt pyqt5 png

我有同时显示的图片列表。它们都在for循环中拾取,并添加到列表中。

不幸的是,某些PNG已损坏。我无法提前告知哪些已损坏,也没有机会转换此类PNG。

必须有一种忽略错误的PNG并跳过它们的方法。

目前,我的代码如下所示:

for file in os.listdir(path):
        # checking if file is png format
        if file.endswith('.png'):
            pic             = os.path.join(self.path_selected, file)
            img_label       = qtw.QWidget()
            pixmap          = qtg.QPixmap(pic).scaledToWidth(img_width)

            img_label.setPixmap(pixmap)
            self.img_mosaique.layout().addWidget(img_label, img_row_count, img_col_count)

            # Adding paths of images to a list
            self.img_mosaique.set_image_path(pic)

如您所见,目前我还在添加错误图片。

据我了解,libpng不会抛出任何异常。我找到了使用此解决方案
try:
    Image.open(path).tobytes()
except IOError:
    print('detect error img %s' % path)
    continue

资料来源:libpng warning: Ignoring bad adaptive filter type

我无法使用此解决方案。

最佳答案

出于效率原因,Qt不会使用异常来表示失败,而是通过其他方式来表示,如果QPixmap加载损坏的图像,这将返回一个空QPixmap,因此您只需要进行验证即可。

for file in os.listdir(path):
    if file.endswith(".png"):
        pic = os.path.join(self.path_selected, file)
        img_label = qtw.QWidget()
        pixmap = qtg.QPixmap(pic)
        if pixmap.isNull():
            continue
        img_label.setPixmap(pixmap.scaledToWidth(img_width))
        self.img_mosaique.layout().addWidget(img_label, img_row_count, img_col_count)
        self.img_mosaique.set_image_path(pic)

关于python - 如何在PyQt5中捕获libpng错误错误的自适应滤波器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60741036/

相关文章:

c++ - 尝试分配输出以查看指针和引用输出时,未命名类型错误

python - PyQt:在窗口上显示 QTextEdits

python - 为什么 [[]]*10 是在 python 中创建 10 个空列表的列表而不是 [[]*10] 的方法?

python - 尝试从字符串列中提取点之间的字符串值

ruby-on-rails - RVM故障排除

python - 如何更改标题数据

python - 将 vtkTimerCallback 与 QVTKRenderWindowInteractor 一起使用不起作用

python - 如何在 matplotlib mplot3D 或类似文件中显示 3D 数组等值面的 3D 图?

Python - 法语年份/数字发音器

vba - 保护非空单元格VBA