Last active
February 6, 2017 15:03
-
-
Save damc-dev/5eb9b0293d888a8ffc24fde915b99493 to your computer and use it in GitHub Desktop.
Optimize Gifs with giflossy
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
#!/bin/groovy | |
import groovy.io.FileType | |
def optimize(inGif, outDir) { | |
def cmd = "gifsicle --colors 256 -O3 ${inGif.path} -o ${outDir.path}\\${inGif.name}" | |
//println cmd | |
def proc = cmd.execute() | |
proc.text.eachLine {println it} | |
def exitValue = proc.exitValue() | |
if (exitValue) { | |
println "Failed executing gifsicle" | |
println cmd | |
println "exitValue: ${exitValue}" | |
} | |
return new File(outDir, inGif.name) | |
} | |
def lossy(inGif, outDir, level) { | |
def cmd = "gifsicle -O3 --lossy=${level} ${inGif.path} -o ${outDir.path}\\${inGif.name}" | |
//println cmd | |
def proc = cmd.execute() | |
proc.text.eachLine {println it} | |
def exitValue = proc.exitValue() | |
if (exitValue) { | |
println "Failed executing gifsicle" | |
println cmd | |
println "exitValue: ${exitValue}" | |
} | |
return new File(outDir, inGif.name) | |
} | |
def removeSpaces = {content -> content.replaceAll(" ", "")} | |
def maxbytesize=512000 | |
def inDir = new File("toOptimize") | |
def outDir = new File("optimized") | |
def failDir = new File("failed") | |
def inGifs = [] | |
outDir.mkdir() | |
failDir.mkdir() | |
inDir.eachFileRecurse(FileType.FILES) { file -> | |
inGifs << file | |
} | |
inGifs.each { inGif -> | |
if (inGif.name.contains(" ")) { | |
inGif.renameTo(removeSpaces(inGif.name)) | |
} | |
def reductionLevel = 0 | |
def result = optimize(inGif, outDir); | |
if (result.length() > maxbytesize) { | |
(2..20).find { level -> | |
reductionLevel = level * 10 | |
result = lossy(inGif, outDir, reductionLevel) | |
//println result.length() | |
if (result.length() < maxbytesize) { | |
return true | |
} | |
return false | |
} | |
} | |
if (result.length() < maxbytesize) { | |
println "${inGif.name} using lossy ${reductionLevel} reduced to ${result.length()} bytes" | |
inGif.delete() | |
} else { | |
println "${inGif.name} could not be optimized" | |
inGif.renameTo(new File(failDir, inGif.name)); | |
result.delete() | |
} | |
} | |
println "Done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment