Skip to content

Instantly share code, notes, and snippets.

@skittleson
Created August 29, 2025 22:54
Show Gist options
  • Select an option

  • Save skittleson/c2b5c23c697b0447000cb61b04740bfd to your computer and use it in GitHub Desktop.

Select an option

Save skittleson/c2b5c23c697b0447000cb61b04740bfd to your computer and use it in GitHub Desktop.
batch process images for color eink
# 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