Unsupported image format error though images are all there

Question:

folder_dir = "Pieces"

print(os.listdir(folder_dir))

for image in os.listdir(folder_dir):
    img.append(pygame.transform.scale(pygame.image.load(f"Pieces/{image}").convert_alpha(), (dimensions[0]/8, dimensions[1]/8)))

I’m trying to load a list of images for my game but it keeps giving me this error:

File "/Users/ragesh/Desktop/Coding_Work/ChessAI/main.py", line 31, in <module>
    img.append(pygame.transform.scale(pygame.image.load(f"Pieces/{image}").convert_alpha(), (dimensions[0]/8, dimensions[1]/8)))
                                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pygame.error: Unsupported image format

I have a folder called "Chess AI" with a python script and a folder called "Pieces". The "Pieces" folder has the images I’m trying to access. Images are in a .png format.

When I do img.append(pygame.transform.scale(pygame.image.load("Pieces/WK.png").convert_alpha(), (dimensions[0]/8, dimensions[1]/8))) it works but the above code doesn’t work.

I’ve tried tinkering around with the directories and changing the loop but nothing works.
Please help.

Asked By: Coder

||

Answers:

"Unsupported image format" means that the image is there, but the format of the image is not supported by your system or the image file is corrupted. os.listdir gives you all files and subdirectories in the folder not just the image files. So you try to load a file that’s not an image. You have to test the file extension:

for image in os.listdir(folder_dir):

png_files = [f for f in os.listdir(folder_dir) if f.endswith('.png')]
for image in png_files:
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.