我有同时显示的图片列表。它们都在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/