Last active
November 30, 2017 20:59
-
-
Save lostplesed/11239503 to your computer and use it in GitHub Desktop.
use tinypng api to compress png file in a directory
This file contains 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" | |
uri = URI.parse("https://api.tinypng.com/shrink") | |
http = Net::HTTP.new(uri.host, uri.port) | |
http.use_ssl = true | |
dir = Dir.pwd | |
index = 0 | |
num = 0 | |
keys = [ | |
"-KmDIUKv8JKK1Iw76hYH4jdw4_HD-9Vw", | |
"J4G6ciq5ARp-bYprzVMc-U9EPwppFRYL", | |
"w37EvdOnWwZGeVSyiJHbfny0_QACxUVO" | |
] | |
limit = 498 | |
def traverse_dir(file_path) | |
if File.directory? file_path | |
Dir.foreach(file_path) do |file| | |
if file!="." and file!=".." | |
traverse_dir(file_path+"/"+file){|x| yield x} | |
end | |
end | |
else | |
yield file_path | |
end | |
end | |
traverse_dir(dir){|f| | |
if f.to_s() =~ /\.png$/ | |
input = f.to_s() | |
output = f.to_s() | |
request = Net::HTTP::Post.new(uri.request_uri) | |
request.basic_auth("api", keys[index]) | |
response = http.request(request, File.read(input)) | |
if response.code == "201" | |
File.write(output, http.get(response["location"]).body) | |
puts "num = " + "#{num}" + " key = " + keys[index] + " 压缩成功 " + "#{output}" | |
else | |
puts "num = " + "#{num}" + " key = " + keys[index] + " 压缩失败 " + "#{output}" | |
end | |
num = num + 1 | |
if num >= limit | |
num = 0 | |
index = index + 1 | |
end | |
end | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
:v