图片优化是网站优化的重要环节。图片优化不但可以节省网站的带宽,最主要的是可以提高页面加载速度,提升用户体验。

本文介绍一款的图片优化工具 image_optim

image_optim

image_optim可以优化(无损压缩)jpeg、png、gif。具体功能通过调用外部工具实现:

安装

gem install image_optim

安装依赖

Linux - Debian/Ubuntu

sudo apt-get install -y advancecomp gifsicle jhead jpegoptim libjpeg-progs optipng pngcrush

Linux - RHEL/Fedora/Centos

sudo yum install -y advancecomp gifsicle jhead libjpeg optipng

你可能需要编译安装jpegoptimpngcrush

jpegoptim
cd /tmp
curl -O http://www.kokkonen.net/tjko/src/jpegoptim-1.2.4.tar.gz
tar zxf jpegoptim-1.2.4.tar.gz
cd jpegoptim-1.2.4
./configure && make && make install
pngcrush
cd /tmp
curl -O http://iweb.dl.sourceforge.net/project/pmt/pngcrush/1.7.43/pngcrush-1.7.43.tar.gz
tar zxf pngcrush-1.7.43.tar.gz
cd pngcrush-1.7.43
make && cp -f pngcrush /usr/local/bin

OS X

Macports

sudo port install advancecomp gifsicle jhead jpegoptim jpeg optipng pngcrush

Brew

brew install advancecomp gifsicle jhead jpegoptim jpeg optipng pngcrush

使用

shell

image_optim *.{jpg,png,gif}

image_optim -h

ruby

初始化

image_optim = ImageOptim.new

image_optim = ImageOptim.new(:pngout => false)

image_optim = ImageOptim.new(:nice => 20)

优化图片

image_optim.optimize_image('a.png')

优化图片(替换原文件)

image_optim.optimize_image!('b.jpg')

多个文件

image_optim.optimize_images(Dir['*.png']) do |unoptimized, optimized|
  if optimized
    puts "#{unoptimized} => #{optimized}"
  end
end

image_optim.optimize_images!(Dir['*.*'])

Rails

config.assets.compress设为trueImageOptim::Railtie会自动处理图片资源。

项目主页


编撰 SegmentFault


weakish
24.6k 声望844 粉丝

a vigorously lazy deadbeat with matured immaturity