Skip to content

Instantly share code, notes, and snippets.

@HyphenSam
Last active November 19, 2018 13:20
Show Gist options
  • Save HyphenSam/258620ed82abff21ee0acb88146b37a5 to your computer and use it in GitHub Desktop.
Save HyphenSam/258620ed82abff21ee0acb88146b37a5 to your computer and use it in GitHub Desktop.
This trims Anilist portraits by n pixels on all sides (default 2).
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.")
@HyphenSam
Copy link
Author

HyphenSam commented Nov 19, 2018

Doesn't work for .png files yet. Will fix later.
Fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment