Class: TinyPngImage

Inherits:
Object
  • Object
show all
Defined in:
lib/script_source/imageTinypng.rb

Instance Method Summary collapse

Instance Method Details

#get_all_img(items) ⇒ Object

正则匹配所有图片资源



6
7
8
9
# File 'lib/script_source/imageTinypng.rb', line 6

def get_all_img(items)
    filter = /[\s\S]*\.(png|jpeg|jpg|pjpg|svg)/
    items.select { |i| i[filter] }
end

#get_configObject

通过本地配置文件获取tinypng的key



17
18
19
20
21
22
23
24
25
# File 'lib/script_source/imageTinypng.rb', line 17

def get_config 
    configPath = ".git/hbh_git_config"
    if !File.exist?(configPath)
        File.new(configPath, "w+").syswrite(template_hash().to_yaml) 
    end

    config = OpenStruct.new YAML.load_file(configPath)
    config.tinypng_key
end

#start_tinypngObject

根据条件开始使用tinypng压缩图片



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/script_source/imageTinypng.rb', line 27

def start_tinypng
    tinypng_key = get_config()

    if !tinypng_key.nil? && !tinypng_key.empty?
        Tinify.key = tinypng_key
        # diffFile = %x(git diff --cached --name-only --diff-filter=ACM)
        diffFile = %x(git diff --cached --name-only --diff-filter=ACM -- '*.jpg' '*.png' '*.jpeg')
        diffArr = diffFile.split("\n")
        imgArr = get_all_img(diffArr)
        if imgArr.count > 0
            puts "开始使用tinypng压缩图片"
            for item in imgArr do
                fileSize =%x(du -sh #{item})
                puts "原文件大小:#{fileSize}"
                Tinify.from_file("#{item}").to_file("#{item}")
                addChangeFile = %x(git add #{item})
                optimizedFileSize =%x(du -sh #{item})
                puts "压缩后文件:#{optimizedFileSize}"
            end
        end
    else
        puts "请到.git/hbh_git_config文件里配置tinypng_key"
        system("open .git/hbh_git_config")
    end
end

#template_hashObject



10
11
12
13
14
15
# File 'lib/script_source/imageTinypng.rb', line 10

def template_hash
    {
    'info' => "配置tinypng_key, 可访问获取对应Key https://tinypng.com/",
    'tinypng_key' => "",
    }  
end