from single jpg to web conversion to all files in dir

98 Views Asked by At

i made python code to convert jpg into webp

from PIL import Image
import PIL
import os
import glob



# Open The Image:
image_path = "D:/..../image_name.jpg"

image = Image.open(image_path)


# Convert the image to RGB Colour:
image = image.convert('RGB')

# Save The Image as webp:
new_image_path = "D:/.../converted_image_name.webp"

image.save(new_image_path, 'webp')

#open converted image for inspection

new_image = Image.open(new_image_path)
new_image.show()

Don't know how to build a function that does the conversion for all files in folder, keeping the orginial file_names.

2

There are 2 best solutions below

7
Stanley Ulili On

Here is a working solution to your problem:

from pathlib import Path

from PIL import Image
import PIL
import os
import glob

# the path to the directory containing the images
directory_path = 'D:\PATH'

def convert_images(directory_path):
    for image_path in os.listdir(directory_path):
        if image_path.endswith(".jpg"):
            image = Image.open(os.path.join(directory_path, image_path))
            # get image filename without an extension
            name = Path(image_path).stem
            rgb_image = image.convert('RGB')
            new_image_path = f"{name}.webp"
            rgb_image.save(os.path.join(directory_path, new_image_path), 'webp')
            new_image = Image.open(new_image_path)
            new_image.show()
            continue
        else:
            continue


convert_images(directory_path)
0
Ron Kieftenbeld On

final code

from pathlib import Path

from PIL import Image
import PIL
import os
import glob

# the path to the directory containing the images
directory_path =  'D:/Lokale schijf/SS2023/Python_API_imports/'


def convert_images(directory_path):
    for image_path in os.listdir(directory_path):
        if image_path.endswith(".jpg"):
            image = Image.open(os.path.join(directory_path, image_path)) 
            # get image filename without an extension
            name = Path(image_path).stem
            rgb_image = image.convert('RGB')
            new_image_path = f"{name}.webp"
            rgb_image.save(os.path.join(directory_path, new_image_path), 'webp') 
            new_image = Image.open(new_image_path)
            new_image.show()
            continue
        

convert_images(directory_path)