cigarginger

PNG to JPG Converter - Recursive

Feb 12th, 2025
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.22 KB | Source Code | 0 0
  1. #Requires Python
  2. #Requires you run the command "pip install pillow"
  3. #Recursively converts all PNG files to JPG of the specified width
  4. #By Marshall Evans https://openmycard.link/marshallevans
  5.  
  6. from PIL import Image
  7. import os
  8.  
  9. def process_image(input_path, output_path, max_width):
  10.     with Image.open(input_path) as img:
  11.         # Convert to RGB mode (removing alpha channel if present)
  12.         if img.mode in ('RGBA', 'LA'):
  13.             background = Image.new('RGB', img.size, (255, 255, 255))
  14.             if img.mode == 'RGBA':
  15.                 background.paste(img, mask=img.split()[3])
  16.             else:
  17.                 background.paste(img, mask=img.split()[1])
  18.             img = background
  19.        
  20.         # Calculate new dimensions
  21.         width_percent = max_width / float(img.size[0])
  22.         if width_percent < 1:
  23.             new_width = max_width
  24.             new_height = int(float(img.size[1]) * width_percent)
  25.             img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
  26.        
  27.         # Save as JPG
  28.         img.save(output_path, 'JPEG', quality=90)
  29.  
  30. def convert_png_to_jpg(root_dir, max_width):
  31.     for dirpath, dirnames, filenames in os.walk(root_dir):
  32.         for filename in filenames:
  33.             if filename.lower().endswith('.png'):
  34.                 input_path = os.path.join(dirpath, filename)
  35.                 output_filename = os.path.splitext(filename)[0] + '.jpg'
  36.                 output_path = os.path.join(dirpath, output_filename)
  37.                
  38.                 try:
  39.                     process_image(input_path, output_path, max_width)
  40.                     print(f"Converted: {input_path} -> {output_path}")
  41.                 except Exception as e:
  42.                     print(f"Error processing {input_path}: {e}")
  43.  
  44. if __name__ == "__main__":
  45.     directory = input("Enter the directory path to process: ")
  46.     while True:
  47.         try:
  48.             max_width = int(input("Enter the maximum width in pixels: "))
  49.             if max_width > 0:
  50.                 break
  51.             print("Please enter a positive number.")
  52.         except ValueError:
  53.             print("Please enter a valid number.")
  54.    
  55.     convert_png_to_jpg(directory, max_width)
  56.     print("\nConversion complete!")
Advertisement
Add Comment
Please, Sign In to add comment