Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from PIL import Image
- import os
- # Set the path to the folder containing the images
- folder_path = '/path/to/folder'
- # Get a list of all the files in the folder
- file_list = os.listdir(folder_path)
- # Loop through each file in the folder
- for filename in file_list:
- # Check if the file is an image
- if filename.endswith('.jpg') or filename.endswith('.jpeg') or filename.endswith('.png'):
- # Open the image file
- img = Image.open(os.path.join(folder_path, filename))
- # Check if the image has an alpha channel (transparency)
- if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
- # Create a new background image
- background = Image.new('RGB', img.size, (255, 255, 255))
- # Composite the transparent image onto the new background
- background.paste(img, mask=img.convert('RGBA').split()[-1])
- # Save the new image with a white background
- background.save(os.path.join(folder_path, filename))
- else:
- # If the image doesn't have an alpha channel, just save it as-is
- img.save(os.path.join(folder_path, filename))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement