使用pngout批量压缩png

pngout是一个基于命令行的对png进行极限压缩的程序,它会去除软件在生成png时加入的额外信息,所以压缩的时候是无损压缩,可以有效降低png容量,又不用担心会失真。

 

pngout可以在这里下载和查看文档:http://advsys.net/ken/util/pngout.htm

 

在命令行里这样使用pngout:

 

D:/pngout.exe sourcepath resultpath

 

第二个参数可以省略,这样会直接覆盖原来的文件。

 

可以用ruby配合pngout来批量处理png图片,其实只需要加一个文件遍历,然后在ruby中调用命令行命令即可:

 

    require 'find'
    require 'fileutils'
    source, result = "D:/source/", "D:/result/"
    Find.find(source) do |file|
      if(!File.directory?(file) && File.extname(file) == ".png")
        IO.popen("d:/pngout.exe " + file + " " + result + File.basename(file)) { |f| puts "converting..." + file}  
      end
    end

 

平时用到一两个png的时候,去操作命令行或者运行ruby脚本都很麻烦,那干嘛不做一个自动压缩的脚本呢?

 

原理很简单,设置一个文件夹,用ruby遍历它,例如3秒遍历一次,发现有文件被修改或者增加了文件,就把文件压缩一下。

 

如此这般,就自动化了,在你保存png之后,只需要等一小会,即可被压缩好,中间不用任何多余操作。

 

判断文件是否被修改是根据文件最后修改时间来的。

 

    require 'find'
    require 'fileutils'

    dir = "d:/source";
    time_record = {}

    def pngout dirname
      if(!File.directory?(dirname) && File.extname(dirname) == ".png")
        IO.popen("d:/pngout.exe " + dirname) { |f| puts "converting..." + dirname }
      end
    end

    begin
      Find.find(dir) do |file|
        begin
          if (!time_record.has_key?(file))
            pngout(file)
            time_record[file] = File.mtime(file)
          else 
            if(time_record[file] != File.mtime(file))
              pngout(file)
              time_record[file] = File.mtime(file)
            end
          end
        rescue
        end
      end
    end while sleep 3

 

你可能感兴趣的:(.net,脚本,F#,Ruby)