TeaDrinker
TeaDrinker

Reputation: 309

Python image conversion script converts some files properly but not others

I'm working on a script to go through a folder full of pictures and do two things. For the purposes of this question, I'm only focusing on the 1st.

This is to convert any .png files into .jpg.

The script is a follows

from PIL import Image
import os,sys

# Check if a filepath was provided
if len(sys.argv)!=2:
    print("Please enter one filepath")
    sys.exit(1)
else:
    directory=sys.argv[1]
    
number_pictures=0
number_errors=0

# converts any non .jpg file into a .jpg
def convert_to_jpg():
    name,ext = os.path.splitext(full_path)
    new_file_name=name+".jpg"
    try:
        with Image.open(full_path) as image:
            image.save(new_file_name)
    except OSError:
        print("ERROR!\nUnable to convert file: "+new_file_name)


def resizeImage():
    print("Hello")


# Iterates through the folder and calls the appropriate method/s based
# on certain characteristics.
for root, dirs, files in os.walk(directory,topdown=True,followlinks=False):
    for file in files:
        if file.endswith('.png'):
            full_path=root+file
            convert_to_jpg()
            number_pictures+=1

print(str(number_pictures))

Please ignore the resizeImage function as it's obviously not ready yet.

The script (mostly) works and does iterate through the file given in the filepath. It does make an attempt to convert every file in the folder to a .jpg but as you can see in the pictures below, it seems to only get about half of them converted properly.

enter image description here

As you can see, my test folder included 10 .png pictures with various names. Some have spaces, some are in all lowercase and others have capital letters.

enter image description here

Here you can see that of the 9 files processed (still figuring out why the one isn't being processed) there are 5 that return errors.

enter image description here

The result in the picture folder is 9 new files (the Capture.png file wasn't processed) and of them, only 4 work correctly. The .jpg files with green placeholder icons return metadata errors.

There doesn't seem to be any rhyme or reason to why the pictures aren't working and I don't know enough about the process behind the file conversion process to guess what is happening.

Any help would be greatly appreciated!

Upvotes: 2

Views: 306

Answers (1)

TeaDrinker
TeaDrinker

Reputation: 309

The issue was a lack of knowledge about the finer points of how images work on a technical level.

I learned from [this page][4] that the issue was coming from an incompatibility of the RGB values (or lack thereof) in the image files. When I changed the code

with Image.open(full_path) as image:
    image.save(new_file_name)

to

with Image.open(full_path).convert('RGB') as image:
    image.save(new_file_name)

It solved the issue instantly.

Upvotes: 1

Related Questions