Skip to content

Instantly share code, notes, and snippets.

@WiggleWizard
Created October 16, 2015 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WiggleWizard/d64f211125c6e1b5e97c to your computer and use it in GitHub Desktop.
Save WiggleWizard/d64f211125c6e1b5e97c to your computer and use it in GitHub Desktop.
Small Scripts
#!/usr/bin/env python
##
# Example: $ ./sizencrop.py -w 90 -h 90 -y -i test/*.jpg
# [+] Cropping a.jpg to 90x90
# \ Done, saved to a.jpg
# [+] Cropping b.jpg to 90x90
# \ Done, saved to b.jpg
##
BIN_IMAGICK = "convert"
import sys
import os
import glob
import subprocess
def crop_image(src, dest, w, h, cover=True):
str_width = "" if width == 0 else str(width)
str_height = "" if height == 0 else str(height)
cmd = [
BIN_IMAGICK,
src,
"-thumbnail", str_width + "x" + str_height + "^",
"-gravity", "center",
"-extent", str_width + "x" + str_height,
dest
]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate()
if proc.returncode == 0:
return out
else:
raise Exception(err)
# Set by CLI
width = 0
height = 0
prefix = ""
suffix = ""
overwrite = False
src_offset = 0
for i, arg in enumerate(sys.argv):
if arg == '-w':
width = int(sys.argv[i + 1])
elif arg == '-h':
height = int(sys.argv[i + 1])
elif arg == '-i':
src_offset = i + 1
elif arg == '-p':
prefix = sys.argv[i + 1]
elif arg == '-s':
suffix = sys.argv[i + 1]
elif arg == '-y':
overwrite = True
# If height or width was not specified then just print empty string
str_width = "" if width == 0 else str(width)
str_height = "" if height == 0 else str(height)
# Protects from destructive forces without specifying -y
if suffix == "" and overwrite == False:
suffix = "_" + str_width + "x" + str_height
for f in sys.argv[src_offset:]:
filename, file_ext = os.path.splitext(f)
file_path = os.path.dirname(f)
file_basename = os.path.basename(f)
file_name = os.path.splitext(file_basename)[0]
dest = file_path + "/" + prefix + file_name + suffix + file_ext
print("[+] Cropping " + f + " to " + str_width + "x" + str_height)
crop_image(f, dest, width, height)
print(" \ Done, saved to " + dest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment