Created
April 13, 2023 21:39
-
-
Save crowsonkb/faf0bce4fe968db7b3d470a03ba4958e to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/env python3 | |
"""Pads an image for Bluesky.""" | |
import argparse | |
import math | |
from pathlib import Path | |
from PIL import Image | |
def get_output_size(size, aspect): | |
in_w, in_h = size | |
in_aspect = size[0] / size[1] | |
if in_aspect < aspect: | |
out_w = int(in_h * aspect) | |
out_h = in_h | |
else: | |
out_w = in_w | |
out_h = int(in_w / aspect) | |
return out_w, out_h | |
def main(): | |
parser = argparse.ArgumentParser(description=__doc__) | |
parser.add_argument("image", type=Path, help="the input image") | |
parser.add_argument( | |
"--bg", type=int, nargs=4, default=(0, 0, 0, 0), help="the background color" | |
) | |
args = parser.parse_args() | |
allowed_aspects = [3 / 4, 1.0, 4 / 3] | |
allowed_log_aspects = [math.log(x) for x in allowed_aspects] | |
image = Image.open(args.image).convert("RGBA") | |
# Find the closest aspect ratio | |
log_aspect = math.log(image.size[0] / image.size[1]) | |
aspect_diffs = [abs(log_aspect - x) for x in allowed_log_aspects] | |
out_aspect = allowed_aspects[aspect_diffs.index(min(aspect_diffs))] | |
# Paste into output image | |
out_size = get_output_size(image.size, out_aspect) | |
out_image = Image.new("RGBA", out_size, tuple(args.bg)) | |
paste_x = (out_size[0] - image.size[0]) // 2 | |
paste_y = (out_size[1] - image.size[1]) // 2 | |
out_image.paste(image, (paste_x, paste_y)) | |
# Save the output image | |
out_path = args.image.with_stem(args.image.stem + "_pad").with_suffix(".png") | |
out_image.save(out_path) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment