Created
May 15, 2017 19:12
-
-
Save hightemp/ea9021743381a30d13de54849b081267 to your computer and use it in GitHub Desktop.
[Ruby] Image minifier
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 ruby | |
fail "[E] Usage:\n\r ruby DIR_NAME <NOP option>\n\r" unless ARGV.first | |
puts "[!] Processing images\n\r" | |
count = 0 | |
sDirectoryName = ARGV.first | |
objDirectory = Dir["#{sDirectoryName}/**/*.{jpg,jpeg,JPG,JPEG,png,PNG}"] # jpg,jpeg,JPG,JPEG, png,PNG | |
iTotalSize = 0.0 | |
iTotalCompressedSize = 0.0 | |
iTotalRatio = 0.0 | |
def fnConvert(in_sFilePath) | |
sTemporaryDirPath = Dir.tmpdir() | |
sFileName = File.basename(in_sFilePath) | |
sTemporaryFilePath = "#{sTemporaryDirPath}/#{sFileName}" | |
sEscapedFilePath = Regexp.escape(in_sFilePath) #.gsub(/[ \/\\\(\)]/, '\\$1') | |
sEscapedTemporaryFilePath = Regexp.escape(sTemporaryFilePath) | |
print("[!] Convert #{sEscapedFilePath}\n\r") | |
# `convert -strip -interlace Plane -quality 60% #{sEscapedFilePath} #{sEscapedTemporaryFilePath}` | |
sResult = `identify ` | |
end | |
def fnHuminifySize(in_iSize) | |
aPrefixes = ['', 'K', 'M', 'G', 'T'] | |
iIterator = 0 | |
fSize = in_iSize.abs | |
while fSize>1024.0 do | |
fSize = fSize/1024.0 | |
iIterator += 1 | |
end | |
return "#{fSize.round(2)} #{aPrefixes[iIterator]}B " | |
end | |
aFiles = { "hFiles" => {}, "iSize" => 0.0 } | |
objDirectory.each do |sFilePath| | |
aFiles["hFiles"][sFilePath] = { | |
"sFileName" => sFilePath, | |
"iSize" => File.size(sFilePath) | |
} | |
aFiles["iSize"] += File.size(sFilePath) | |
end | |
print("Files: #{aFiles["hFiles"].length} Total size: #{fnHuminifySize(aFiles["iSize"])}\n\r") | |
exit() | |
objDirectory.each do |sFilePath| | |
iOldFileSize = File.size(sFilePath) | |
if (iOldFileSize/(1024.0*1024.0) > 1.0) | |
count += 1 | |
fnConvert(sFilename) | |
iNewFileSize = File.size(sFilePath) | |
fCompressRatio = ((iOldFileSize - iNewFileSize)/iOldFileSize).abs*100.0 | |
print("[!] Size:#{fnHuminifySize(iNewFileSize)} Old size:#{fnHuminifySize(iOldFileSize)} Ratio:#{fCompressRatio}\n\r") | |
iTotalSize += iOldFileSize | |
iTotalCompressedSize += iOldFileSize - iNewFileSize | |
fTotalRatio = (iTotalCompressedSize/iTotalSize).abs*100.0 | |
print("[!] Total size:#{fnHuminifySize(iTotalSize)} Compressed size:#{fnHuminifySize(iTotalCompressedSize)} Ratio:#{fTotalRatio}\n\r") | |
exit() | |
end | |
end | |
puts "[!] Completed: #{count} files processed..\n\r" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment