图片压缩脚本

通过 tinypng 提供的 api 批量压缩工程中 xcassets 的图片。对于已压缩的图片,在图片的 exif 信息中添加 Comment 字段,防止重复压缩操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def isImageCompressed(path)
require 'rmagick'
image = Magick::Image.read(path).first
result = image["Comment"]
return false if result.nil?
result.include?("Compressed by tinypng")
end

def recordImageCompressed(path)
require 'rmagick'
image = Magick::Image.read(path).first
commnet = image["Comment"].nil? ? "" : "#{image["Comment"]}\n"
image["Comment"] = commnet + "Compressed by tinypng"
image.write(path)
end

desc "压缩图片"
lane :compress_images do
require "tinify"
Dir.chdir ".."
require "json"
require "tinify"
keys = ["key1", "key2", "key3"]
Tinify.key = keys[0]

puts "图片检索中..."
exclude_dirs = ["Pods", "*.bundle"].map { |d| "./dealer/**/#{d}/**/*.{png,jpg}" }
images = Dir.glob("./dealer/**/*.{png,jpg}")
images -= Dir.glob(exclude_dirs)
images = images.select { |image| !isImageCompressed(image) }
puts "待压缩图片数量: #{images.count}"
images.each_with_index { |f, i|
puts "正在处理图片: #{f}"
begin
Tinify.from_file(f).to_file(f)
recordImageCompressed(f)
key_index = (i + 1) / 500
if key_index < keys.count
Tinify.key = keys[key_index]
else
puts "key 用完了, 快给我新 key (●゚ω゚●)"
break
end
rescue => exception
puts "😭 #{f} 压缩失败了,失败原因: #{exception}"
break
end
}
end