一丶
有時(shí)候項(xiàng)目工程太大,可以利用tinify 提供的api,進(jìn)行壓縮
二丶 準(zhǔn)備工作
$gem install tinify
2.申請(qǐng)Key
三丶代碼
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
require "tinify" # gem install tinify
DIR_PATH = "文件夾路徑"
TINIFY_KEY = "申請(qǐng)的key" #https://tinypng.com/dashboard/api
Tinify.key = TINIFY_KEY
class ImageManager
def initialize(path = "")
@root_path = path
@imageSize_total = 0
@all_imagePaths = []
traverse(@root_path )
puts "\033[31m------------ begin ------------\033[0m\n"
puts "準(zhǔn)備壓縮文件列表:"
@all_imagePaths.each { |filePath|
puts File.basename(filePath).to_s
}
end
def calculate_image_total
@imageSize_total = 0
@all_imagePaths.each { |filePath|
@imageSize_total = @imageSize_total + File.size(filePath)/1024.0
}
end
def handle_image(filePath)
puts "\033[32m >>>>正在壓縮圖片 : #{File.basename(filePath) } \033[0m\n"
old_size = (File.size(filePath)/1024.0).to_s
source = Tinify.from_file(filePath)
source.to_file(filePath)
new_size = (File.size(filePath)/1024.0).to_s
puts "壓縮前: #{old_size} 壓縮后: #{new_size}"
end
def traverse(filepath)
if File.directory?(filepath)
Dir.foreach(filepath) do |filename|
if filename != "." and filename != ".."
traverse(filepath + "/" + filename)
end
end
else
if File.extname(filepath) == ".png"
@all_imagePaths << filepath
end
end
end
#compress_pictures
def run
puts "---------------->"
calculate_image_total
puts "壓縮前圖片總大小: " + format("%.2f", @imageSize_total) + " KB"
@all_imagePaths.each { |filePath|
handle_image(filePath)
}
calculate_image_total
puts "壓縮后圖片總大小: " + format("%.2f", @imageSize_total) + " KB"
puts "<----------------"
self.end
end
def end
puts "\033[31m------------ end ------------\033[0m\n"
end
end
imgM = ImageManager.new(DIR_PATH)
imgM.run
四 丶
壓縮前:
壓縮后:
五 丶
https://github.com/k373379320/ZBScript/blob/master/Ruby/project_handle_resource.rb