項目圖片無損壓縮腳本

一丶

有時候項目工程太大,可以利用tinify 提供的api,進(jìn)行壓縮

二丶 準(zhǔn)備工作

$gem install tinify

2.申請Key

https://tinypng.com/dashboard/api

三丶代碼

#!/usr/bin/ruby
# -*- coding: utf-8 -*-

require "tinify" # gem install tinify

DIR_PATH = "文件夾路徑"
TINIFY_KEY = "申請的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

四 丶

壓縮前:


image.png

壓縮后:


,

五 丶

https://github.com/k373379320/ZBScript/blob/master/Ruby/project_handle_resource.rb

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容