Created
October 7, 2011 10:02
-
-
Save clemesha/1269950 to your computer and use it in GitHub Desktop.
Download, resize image without ruining aspect ration. OSX specific
This file contains hidden or 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 python | |
""" | |
Quick hack to download an image, then resize to a smaller image | |
that does not ruin the aspect ratio of the original image. | |
NOTE: The script is OS X specific: uses commands 'sips' and 'file'. | |
""" | |
import sys | |
import commands #deprecated in Python 3 - use 'subprocess' module | |
BASE_IMAGE_URL = "http://example.com/%s" | |
def get_width_height(image_name): | |
widthstr = commands.getstatusoutput("sips -g pixelWidth %s " % image_name)[1] | |
heightstr = commands.getstatusoutput("sips -g pixelHeight %s " % image_name)[1] | |
width = int(widthstr.split("pixelWidth: ")[1]) | |
height = int(heightstr.split("pixelHeight: ")[1]) | |
return [width, height] | |
def crop_to_min(image_name, width, height): | |
cropto = height | |
if width <= height: cropto = width | |
cmd = "sips --cropToHeightWidth %d %d %s" % (cropto, cropto, image_name) | |
print "Running: %s ..." % cmd | |
result = commands.getstatusoutput(cmd) | |
return result | |
def crop_resize_square(image_name, size=200): | |
width, height = get_width_height(image_name) | |
result0 = crop_to_min(image_name, width, height) | |
cmd = "sips --resampleHeightWidth %d %d %s" % (size, size, image_name) | |
result1 = commands.getstatusoutput(cmd) | |
result2 = commands.getstatusoutput("du -h %s " % image_name)[1] | |
return result2 | |
def get_image_for_url(imagepath): | |
url = BASE_IMAGE_URL % imagepath | |
print "getting: %s " % url | |
real_image_url = "http://" + commands.getstatusoutput("curl %s " % (url, ))[1].split("http://")[1] | |
print real_image_url | |
result1 = commands.getstatusoutput("curl %s > %s.tempfile" % (real_image_url, imagepath)) | |
filetype = commands.getstatusoutput("file %s.tempfile" % imagepath)[1] | |
if "JPEG" in filetype: ext = ".jpg" | |
if "PNG" in filetype: ext = ".png" | |
filename = imagepath.lower() + ext | |
result1 = commands.getstatusoutput("mv %s.tempfile %s" % (imagepath, filename)) | |
return filename | |
if __name__ == "__main__": | |
imagepath = sys.argv[1] | |
image_name = get_image_for_url(imagepath) | |
print "Result: ", crop_resize_square(image_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment