Skip to content

Instantly share code, notes, and snippets.

@FabianBartl
Created February 7, 2024 11:15
Show Gist options
  • Save FabianBartl/0c9eb341199c56823a3a5df80bad2c38 to your computer and use it in GitHub Desktop.
Save FabianBartl/0c9eb341199c56823a3a5df80bad2c38 to your computer and use it in GitHub Desktop.
A script to resize an image of any size while keeping the original aspect ratio.
# A script to resize an image of any size while keeping the original aspect ratio.
# To keep the output size and the aspect ratio, the free space next to the image
# is filled with a given RGBA color.
from PIL import Image
import sys
import re
# open input image path from 1st cli arg
inimg = Image.open(sys.argv[1]).convert("RGBA")
print("image", sys.argv[1], "opened as rgba")
# read input image size and calculate aspect ratio
insize = inwidth, inheight = inimg.size
aspectratio = inwidth / inheight
print("read input image width", inwidth, "and height", inheight, "with calculated aspect ratio (w/h)", aspectratio)
# parse output image size from 2nd cli arg
wstr,hstr = re.findall(r"(\d+),(\d+)", sys.argv[2])[0]
outsize = outwidth, outheight = (int(wstr), int(hstr))
print("will convert to width", outwidth, "and height", outheight)
# calculate in-out image size difference
diffwidth = outwidth - inwidth
diffheight = outheight - inheight
print("in-out image width difference", diffwidth, "and height difference", diffheight)
# get rgba color for inset from 3rd cli arg
clst = re.findall(r"(\d+),(\d+),(\d+),(\d+)", sys.argv[3])[0]
insetcolor = tuple([ int(c) for c in clst ])
print("will inset fill with rgba color", insetcolor)
# get output image path from 4th cli arg
outpath = sys.argv[4]
print("will output image save as", outpath)
# create output image with inset color as background
outimg = Image.new("RGBA", outsize, insetcolor)
# resize input image depending on the orientation
# and place resized image centered on the output image
# for landscape input image
if abs(diffwidth) > abs(diffheight):
print("input image is in landscape orientation")
resimg = inimg.resize((outwidth, int(outheight*aspectratio)))
inset = int((outheight - resimg.height) / 2)
outimg.paste(resimg, (0, inset))
# for portait input image
elif abs(diffwidth) < abs(diffheight):
print("input image is in portrait orientation")
resimg = inimg.resize((int(outwidth*aspectratio), outheight))
inset = int((outwidth - resimg.width) / 2)
outimg.paste(resimg, (inset,0))
# for square input image
else:
print("input image is a square")
resimg = inimg.resize((outwidth, outheight))
# save resized square image (no inset needed) and exit
resimg.save(outpath)
print("resized input image saved")
resimg.show()
exit()
print("resized image composited")
# save composited output image
outimg.save(outpath)
print("output image saved")
outimg.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment