Skip to content

Instantly share code, notes, and snippets.

@pixelrevision
Last active December 21, 2015 11:39
Show Gist options
  • Save pixelrevision/6300470 to your computer and use it in GitHub Desktop.
Save pixelrevision/6300470 to your computer and use it in GitHub Desktop.
Resize iOS images
'''
requires imagemagick to be installed. http://www.imagemagick.org/script/index.php
requires pngquant to be installed if using compression on pngs. http://pngquant.org/
'''
import os
import sys
import subprocess
import argparse
import shutil
import mimetypes
def copyImage(imageIn, imageOut):
shutil.copy(imageIn, imageOut)
def resizeImage(imageIn, imageOut, percentage):
command = ["convert", imageIn, "-resize", percentage, imageOut]
subprocess.call(command)
def compressPNG(imagePath, numberOfColors):
command = ["pngquant", numberOfColors, "--force", "--ext", ".png", imagePath]
subprocess.call(command)
def compressJPG(imagePath, quality):
command = ["convert", "-quality", quality, imagePath]
subprocess.call(command)
print command
def process2xImages(args):
inputDir = args.input
if(inputDir[-1:] != "/"):
inputDir = inputDir + "/"
imagesToProcess = []
fileList = os.listdir(inputDir)
for fileName in fileList:
inputFile = inputDir + fileName
if(validFile(inputFile)):
imagesToProcess.append(inputFile)
outDir = args.output
if(outDir == None):
outDir = inputDir
if(outDir[-1:] != "/"):
outDir = outDir + "/"
totalFiles = len(imagesToProcess)
processed = 0
for image in imagesToProcess:
outImagePath = image.replace(inputDir, outDir)
if(inputDir != outDir):
copyImage(image, outImagePath)
resizedImagePath = outImagePath.replace("@2x", "")
resizeImage(image, resizedImagePath, "50%")
mimetype = mimetypes.guess_type(outImagePath)[0]
if(args.compresspngs == True and mimetype == "image/png"):
compressPNG(outImagePath, args.pngcolors)
compressPNG(resizedImagePath, args.pngcolors)
if(args.compressjpgs == True and mimetype == "image/jpeg"):
compressJPG(outImagePath, args.jpegcompression)
compressJPG(resizedImagePath, args.jpegcompression)
processed += 1
complete = float(processed)/float(totalFiles)
percentageComplete = str(int(complete * 100.0))
outputText = percentageComplete + "% : " + str(processed) + " of " + str(totalFiles)
sys.stdout.write('\r' + outputText)
sys.stdout.flush()
print "\nDone: processed " + str(totalFiles) + " files"
def validFile(filePath):
extension = os.path.splitext(filePath)[1].lower()
valid = False
if(extension == ".png" or extension == ".jpeg" or extension == ".jpg"):
valid = True
if "@2x" not in filePath and valid == True:
valid = False
return valid
def checkArgsAndGetDir(args):
if(args.input == None):
print "Not enough arguments. You need to supply an input directory"
exit(1)
elif os.path.isdir(args.input) == False:
print args.input + " is not a directory"
exit(1)
checkInstalledTools(args)
def checkInstalledTools(args):
# check for image magic
try:
subprocess.check_call(["convert"], stdout=open(os.devnull, "wb"))
except subprocess.CalledProcessError:
print "something went wrong with imagemagick"
exit(1)
except OSError:
print "imagemagick needs to be installed. You can find it at: http://www.imagemagick.org/script/command-line-tools.php"
exit(1)
#check for pngquant if needed
if(args.compresspngs == True):
try:
subprocess.check_call(["pngquant", "-h"], stdout=open(os.devnull, "wb"))
except subprocess.CalledProcessError:
print "something went wrong with pngquant"
exit(1)
except OSError:
print "pngquant needs to be installed. You can find it at: http://pngquant.org/"
exit(1)
def start():
parser = argparse.ArgumentParser(description="A utility to resize retina images for iOS.")
parser.add_argument("-i", "--input", metavar="", required=True, help="The image directory to use for sampling.")
parser.add_argument("-o", "--output", metavar="", required=False, type=str, help="The directory to save the images. If left blank will use the input directory.")
parser.add_argument("-c", "--compresspngs", help="Will compress PNGs if set", action="store_true")
parser.add_argument("-d", "--pngcolors", metavar="", required=False, type=str, default="256", help="Number of colors to use when compressing pngs if compress pngs is on. Default 256.")
parser.add_argument("-j", "--compressjpgs", help="Will compress JPEGs if set", action="store_true")
parser.add_argument("-g", "--jpegcompression", metavar="", required=False, type=str, default="10", help="Compression to use for jpegs. Default 90.")
args = parser.parse_args()
checkArgsAndGetDir(args)
process2xImages(args)
start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment