I have a list of pictures which are displayed simultanously. They are all picked up in a for loop and added to a list.
Unfortunately some PNGs are corrupted. There is no way for me to tell in advance which are corrupted, also there is no chance to convert such PNG.
There must be a way to ignore the faulty PNGs and skip them.
Currently my code looks like this:
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)
As you can see currently I am adding also faulty pictures.
As far as I found out, libpng does not throw any exceptions. I had found a solution to use this
try:
Image.open(path).tobytes()
except IOError:
print('detect error img %s' % path)
continue
Source: libpng warning: Ignoring bad adaptive filter type
I could not make it work with this solution.
Qt for efficiency reasons does not use exceptions to indicate the failures but other means, in the case of QPixmap loading a corrupt image this will return a null QPixmap so you only have to verify that.
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)