Skip to content

Instantly share code, notes, and snippets.

@pixelrevision
Last active December 19, 2015 06:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pixelrevision/5914646 to your computer and use it in GitHub Desktop.
Save pixelrevision/5914646 to your computer and use it in GitHub Desktop.
Process Android images
'''
requires imagemagick to be installed. http://www.imagemagick.org/script/index.php
'''
import os
import sys
import subprocess
import argparse
# defines the input we want to use. Change the directory name or the target DPI to set this.
inputDirName = "drawable-xhdpi"
inputDirSize = 320.0
# the directories we want to output to with the dpi size
outputs = {
"drawable-xxhdpi": 480.0,
"drawable-xhdpi": 320.0,
"drawable-hdpi": 240.0,
"drawable-mdpi": 160.0,
"drawable-ldpi": 120.0
}
def resizeAndSave(imagePath, savePath, resizeAmount):
percentage = str(resizeAmount * 100) + "%"
command = ["convert", imagePath, "-resize", percentage, savePath]
subprocess.call(command)
def resizeImages(inputDirectory):
baseDir = inputDirectory + inputDirName
fileList = os.listdir(baseDir)
imagesToProcess = []
for fileName in fileList:
inputFile = baseDir + "/" + fileName
if(validFile(inputFile)):
imagesToProcess.append(fileName)
totalFiles = len(imagesToProcess)
processed = 0
for fileName in imagesToProcess:
for output in outputs:
if output != inputDirName:
outputDir = inputDirectory + output
if os.path.exists(outputDir) == False:
os.makedirs(outputDir)
percentage = outputs[output]/inputDirSize
inputFile = baseDir + "/" + fileName
outputFile = outputDir + "/" + fileName
resizeAndSave(inputFile, outputFile, percentage)
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()
if(extension == ".png" or extension == ".jpeg" or extension == ".jpg"):
return True
return False
def checkArgsAndGetDir(args):
if(args.resdir == None):
print "Not enough arguments. You need to supply a res directory"
exit(1)
elif os.path.isdir(args.resdir) == False:
print args.resdir + " is not a directory"
exit(1)
inputDirectory = args.resdir
if(args.input != None):
global inputDirName
inputDirName = str(args.input)
inputDirSize = outputs[inputDirName]
if(inputDirectory[-1:] != "/"):
inputDirectory = inputDirectory + "/"
if os.path.isdir(inputDirectory + inputDirName) == False:
print "Res folder contains no " + inputDirName + " directory"
exit(1)
output = {}
return inputDirectory
def checkImageMagick():
# 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)
def start():
parser = argparse.ArgumentParser(description="A utility to resize images for android.")
parser.add_argument("-r", "--resdir", metavar="", required=True, type=str, help="The res directory for the images")
choices = []
helpText = "valid options: "
for key in outputs:
choices.append(key)
helpText += key + " "
parser.add_argument("-i", "--input", metavar="", default="drawable-xhdpi", choices=choices, help="The image directory to use for sampling. " + helpText)
args = parser.parse_args()
checkImageMagick()
inputDirectory = checkArgsAndGetDir(args)
resizeImages(inputDirectory)
start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment