Search code examples
pythonsavepython-imaging-libraryjpegenumerate

Cannot save multiple files with PIL save method


I have modified a vk4 converter to allow for the conversion of several .vk4 files into .jpg image files. When ran, IDLE does not give me an error, but it only manages to convert one file before ending the process. I believe the issue is that image.save() only seems to affect a single file and I have been unsuccessful in looping that command to extend to all other files in the directory.

Code:

import numpy as np
from PIL import Image
import vk4extract
import os

os.chdir(r'path\to\directory')
root = ('.\\')
vkimages = os.listdir(root)

for img in vkimages:
    if (img.endswith('.vk4')):
        with open(img, 'rb') as in_file:
            offsets = vk4extract.extract_offsets(in_file)
            rgb_dict = vk4extract.extract_color_data(offsets, 'peak', in_file)

            rgb_data = rgb_dict['data']
            height = rgb_dict['height']
            width = rgb_dict['width']

            rgb_matrix = np.reshape(rgb_data, (height, width, 3))
            image = Image.fromarray(rgb_matrix, 'RGB')

            image.save('sample.jpeg', 'JPEG')

How do I prevent the converted files from being overwritten while using the PIL module?

Thank you.


Solution

  • It is saving every file, but since you are always providing the same name to each file (image.save('sample.jpeg', 'JPEG')), only the last one will be saved and all the other ones will be overwritten. You need to specify different names to every file. There are several ways of doing it. One is adding the index when looping using enumerate():

    for i, img in enumerate(vkimages):
    

    and then using the i on the name of the file when saving:

    image.save(f'sample_{i}.jpeg', 'JPEG')
    

    Another way is to use the original filename and replace the extension. From your code, it looks like the files are .vk4 files. So another possibility is to save with the same name but replacing .vk4 to .jpeg:

    image.save(img.replace('.vk4', '.jpeg'), 'JPEG')