TinyPng压缩图片的ruby脚本

275 阅读1分钟

背景: Tiny官网只支持当个图片上传后,手动点击下载压缩后的图片;不支持上传文件夹压缩;

方案: 可以自己手撸一个脚本,安装到本地,压缩文件夹中png图片。

  1. 官网查找API_KEY tinify.com/dashboard/a…
  2. 创建tiny脚本 (替换其中的API_KEY)
#使用 $tiny FilePath
require 'json'
# 导入必要的库
require 'pathname'
# 定义一个方法,用于检查文件是否为图片文件
def image_file?(file)
  ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff'].include?(File.extname(file).downcase)
end
# 获取传入的路径参数
path = ARGV[0]
# 检查路径是否存在
unless path && File.directory?(path)
  puts "指定的路径不存在或不是一个目录。"
  exit
end
# 使用Dir类遍历目录中的文件
Dir.foreach(path) do |file|
  next if file.start_with?('.')  # 跳过隐藏文件和目录
  # 使用Pathname类获取文件的完整路径
  file_path = File.join(path, file)
  
  # 检查文件是否为图片文件
  if image_file?(file_path)
    puts "找到图片文件:#{file_path}"
    
    # 执行 curl 命令并获取输出内容
    output = `curl --user api:API_KEY --data-binary @"#{file_path}" -i https://api.tinify.com/shrink`
    puts "curl执行后的output #{output}"
    
    # 解析 JSON 格式的输出内容
    output_url = output.match(/location:\s*(.+)/i)&.captures&.first
    output_url = output_url.chomp
    puts "提取url #{output_url}"
    
    # 创建 output 目录
    output_directory = File.join(path, 'output')
    Dir.mkdir(output_directory) unless Dir.exist?(output_directory)
    
    # 提取图片文件名
    file_name = File.basename(file_path)
    puts "提取图片名 #{file_name}"
    
    # 下载文件到 output 目录
    if output_url
      output_file_path = File.join(output_directory, file_name)
      puts "新图片的输出路径 #{output_file_path}"
      system("curl -o "#{output_file_path}" "#{output_url}" ")
      puts "文件已下载到 #{output_file_path}"
    else
      puts "无法提取下载链接。"
    end
  end
end
  1. 创建快捷指令
# 打开zshrc配置
$ open ~/.zshrc


# 追加下面的内容
tiny() {
ruby /Users/xx/tinypng.rb "$@"
}


# 更新zshrc配置
$ source ~/.zshrc
  1. 使用示例
# 自动将xxFilePath文件夹下的图片,通过tiny压缩并输出到output文件夹内
$ tiny xxFilePath