Created
August 29, 2025 22:54
-
-
Save skittleson/c2b5c23c697b0447000cb61b04740bfd to your computer and use it in GitHub Desktop.
batch process images for color eink
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # encoding: utf-8 | |
| import sys | |
| import os.path | |
| from PIL import Image | |
| directory = 'pics' | |
| def main(): | |
| # Loop through all files in the directory | |
| for filename in os.listdir(directory): | |
| # Construct full file path | |
| file_path = os.path.join(directory, filename) | |
| # Check if it is a file (not a directory) | |
| if os.path.isfile(file_path): | |
| convert(filename) | |
| def convert(input_filename): | |
| input_image = Image.open(os.path.join(directory, input_filename)) | |
| # Get the original image size | |
| width, height = input_image.size | |
| # Specified target size | |
| target_width, target_height = 800, 480 | |
| # Computed scaling | |
| scale_ratio = max(target_width / width, target_height / height) | |
| # Calculate the size after scaling | |
| resized_width = int(width * scale_ratio) | |
| resized_height = int(height * scale_ratio) | |
| # Resize image | |
| output_image = input_image.resize((resized_width, resized_height)) | |
| # Create the target image and center the resized image | |
| resized_image = Image.new("RGB", (target_width, target_height), (255, 255, 255)) | |
| left = (target_width - resized_width) // 2 | |
| top = (target_height - resized_height) // 2 | |
| resized_image.paste(output_image, (left, top)) | |
| # Create a palette object | |
| pal_image = Image.new("P", (1, 1)) | |
| pal_image.putpalette( | |
| (0, 0, 0, 255, 255, 255, 0, 255, 0, 0, 0, 255, 255, 0, 0, 255, 255, 0, 255, 128, 0) | |
| + (0, 0, 0) * 249 | |
| ) | |
| quantized_image = resized_image.quantize(dither=3, palette=pal_image).convert("RGB") | |
| # Save output image | |
| output_filename = os.path.join("output" , (os.path.splitext(input_filename)[0] + "_output.bmp")) | |
| quantized_image.save(output_filename) | |
| print(f"Successfully converted {input_filename} to {output_filename}") | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment