Create a gist now

Instantly share code, notes, and snippets.

@rakuishi /tinypng.rb
Last active Aug 29, 2015

What would you like to do?
# -*- coding: utf-8 -*-
# $ ruby tinypng.rb drawable/
require 'fileutils'
require 'net/https'
require 'uri'
API_KEY = '***'
i_dir = ARGV[0]
o_dir_prefix = 'tinypng_'
FileUtils.mkdir_p(o_dir_prefix + i_dir)
Dir.glob(i_dir + '*.png').each do |image|
uri = URI.parse('https://api.tinypng.com/shrink')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri)
request.basic_auth("api", API_KEY)
response = http.request(request, File.binread(image))
if response.code == "201"
puts "Compression OK: " + image + " => " + o_dir_prefix + image
File.binwrite(o_dir_prefix + image, http.get(response["location"]).body)
else
puts "Compression NG: " + image
end
end
Owner
    gist/
    ├── tinypng.rb
    ├── ARGV[0]/
    └── tinypng_ + ARGV[0]/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment