Created
August 11, 2014 14:50
-
-
Save davidhooey/6f0a39d812ea0c58ff20 to your computer and use it in GitHub Desktop.
Compress PNGs using the TinyPNG service.
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
require "net/https" | |
require "uri" | |
# Ensure we have two parameters. | |
if ARGV.length != 2 | |
puts "Usage: #{$0} input_directory output_directory" | |
exit 1 | |
end | |
key = "PLACE_TINY_PNG_KEY_HERE" | |
input_dir = ARGV[0] | |
output_dir = ARGV[1] | |
# Get an array of PNG files within the input directory. | |
png_files = Dir["#{input_dir}/*.png"] | |
# Exit if there are no PNG files. | |
if png_files.length == 0 | |
puts "No PNG files in #{input_dir}." | |
exit 1 | |
end | |
# Create output directory if it doesn't exsit. | |
Dir.mkdir(output_dir) unless Dir.exists?(output_dir) | |
# We're good to start using tinypng to compress. | |
uri = URI.parse("https://api.tinypng.com/shrink") | |
http = Net::HTTP.new(uri.host, uri.port) | |
http.use_ssl = true | |
png_files.each do |input_file| | |
output_file = "#{output_dir}/#{File.basename(input_file)}" | |
puts "Processing #{input_file} => #{output_file}" | |
request = Net::HTTP::Post.new(uri.request_uri) | |
request.basic_auth("api", key) | |
response = http.request(request, File.binread(input_file)) | |
if response.code == "201" | |
# Compression was successful, retrieve output from Location header. | |
File.binwrite(output_file, http.get(response["location"]).body) | |
puts " -> OK" | |
else | |
# Something went wrong! You can parse the JSON body for details. | |
puts " -> FAILED Compression failed. Exiting." | |
exit 1 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment