Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Requires Python
- #Requires you run the command "pip install pillow"
- #Recursively converts all PNG files to JPG of the specified width
- #By Marshall Evans https://openmycard.link/marshallevans
- from PIL import Image
- import os
- def process_image(input_path, output_path, max_width):
- with Image.open(input_path) as img:
- # Convert to RGB mode (removing alpha channel if present)
- if img.mode in ('RGBA', 'LA'):
- background = Image.new('RGB', img.size, (255, 255, 255))
- if img.mode == 'RGBA':
- background.paste(img, mask=img.split()[3])
- else:
- background.paste(img, mask=img.split()[1])
- img = background
- # Calculate new dimensions
- width_percent = max_width / float(img.size[0])
- if width_percent < 1:
- new_width = max_width
- new_height = int(float(img.size[1]) * width_percent)
- img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
- # Save as JPG
- img.save(output_path, 'JPEG', quality=90)
- def convert_png_to_jpg(root_dir, max_width):
- for dirpath, dirnames, filenames in os.walk(root_dir):
- for filename in filenames:
- if filename.lower().endswith('.png'):
- input_path = os.path.join(dirpath, filename)
- output_filename = os.path.splitext(filename)[0] + '.jpg'
- output_path = os.path.join(dirpath, output_filename)
- try:
- process_image(input_path, output_path, max_width)
- print(f"Converted: {input_path} -> {output_path}")
- except Exception as e:
- print(f"Error processing {input_path}: {e}")
- if __name__ == "__main__":
- directory = input("Enter the directory path to process: ")
- while True:
- try:
- max_width = int(input("Enter the maximum width in pixels: "))
- if max_width > 0:
- break
- print("Please enter a positive number.")
- except ValueError:
- print("Please enter a valid number.")
- convert_png_to_jpg(directory, max_width)
- print("\nConversion complete!")
Advertisement
Add Comment
Please, Sign In to add comment