图片压缩脚本 发表于 2022-05-05 | 分类于 工具 | 通过 tinypng 提供的 api 批量压缩工程中 xcassets 的图片。对于已压缩的图片,在图片的 exif 信息中添加 Comment 字段,防止重复压缩操作。 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849def isImageCompressed(path) require 'rmagick' image = Magick::Image.read(path).first result = image["Comment"] return false if result.nil? result.include?("Compressed by tinypng")enddef 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)enddesc "压缩图片"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