Advertisement
Guest User

Untitled

a guest
Mar 10th, 2023
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.20 KB | None | 0 0
  1. from PIL import Image
  2. import os
  3.  
  4. # Set the path to the folder containing the images
  5. folder_path = '/path/to/folder'
  6.  
  7. # Get a list of all the files in the folder
  8. file_list = os.listdir(folder_path)
  9.  
  10. # Loop through each file in the folder
  11. for filename in file_list:
  12.     # Check if the file is an image
  13.     if filename.endswith('.jpg') or filename.endswith('.jpeg') or filename.endswith('.png'):
  14.         # Open the image file
  15.         img = Image.open(os.path.join(folder_path, filename))
  16.        
  17.         # Check if the image has an alpha channel (transparency)
  18.         if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
  19.             # Create a new background image
  20.             background = Image.new('RGB', img.size, (255, 255, 255))
  21.            
  22.             # Composite the transparent image onto the new background
  23.             background.paste(img, mask=img.convert('RGBA').split()[-1])
  24.            
  25.             # Save the new image with a white background
  26.             background.save(os.path.join(folder_path, filename))
  27.         else:
  28.             # If the image doesn't have an alpha channel, just save it as-is
  29.             img.save(os.path.join(folder_path, filename))
  30.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement