Last active
November 19, 2018 13:20
-
-
Save HyphenSam/258620ed82abff21ee0acb88146b37a5 to your computer and use it in GitHub Desktop.
This trims Anilist portraits by n pixels on all sides (default 2).
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
from PIL import Image | |
import glob, os, sys | |
''' | |
Place images in the "Input" folder for trimming. | |
Results of trimming will be created in the "Output" folder. | |
Input and Output folders will be automatically created if they don't exist. | |
Add a number as an argument to change how many pixels to crop (default 2). | |
''' | |
def trim(im, n): | |
w, h = im.size # Width and height of image | |
return im.crop((n, n, w-n, h-n)) # Crops top-left and bottom-left coordinates by n pixels | |
# Checks if Input and Output folders exist. | |
# There's probably a prettier way of doing this. | |
if not os.path.exists("Input"): | |
os.makedirs("Input") | |
print("Folders created. Place images in the Input folder for trimming.") | |
if not os.path.exists("Output"): | |
os.makedirs("Output") | |
# Sets pixels to crop by user argument. If none exists, use default 2. | |
try: | |
pixels = int(sys.argv[1]) | |
except: | |
pixels = 2 | |
# Initialises list containing images. Order doesn't matter. | |
folder = glob.glob("Input\*.jpg") | |
folder += glob.glob("Input\*.png") | |
num = 0 | |
for i in folder: | |
# Goes through each image in folder and trims it. | |
# Saves results to Output folder. Original file name is retained. | |
num+=1 | |
im = Image.open(i) | |
im = trim(im, pixels) | |
f = i[-3:] # Format of image. Not compatible for file types larger than 3 chars | |
filename = i[6:-4] | |
if f == "jpg": | |
im.save("Output/%s.jpg" % filename, "JPEG", quality=95, optimize=True, progressive=True) | |
elif f == "png": | |
im.save("Output/%s.png" % filename, "PNG", optimize=True) | |
else: | |
print("Unknown image format. Only PNG and JPEG files are compatible.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Doesn't work for .png files yet. Will fix later.Fixed.