Google PageSpeed Insights可以對網頁加載速度評分,並給出優化建議
簡單來說,優化圖片即使用合適尺寸的圖片(縮放,裁剪),壓縮圖片
這里只介紹jpng和png兩種圖片格式
軟件准備:
imagemagick
apt-get install imagemagick
jpegtran
apt-get install libjpeg-turbo-progs
optipng
apt-get install optipng
pngquant
apt-get install pngquant
php5-gd
apt-get install php5-gd
0.格式轉換
一般來說,jpg圖片比png圖片小得多,如無特殊需求(如透明)使用jpg圖片可大大減小圖片大小
格式轉換可使用convert命令
shell_exec('convert a.png a.jpg');
圖片從7百k變成了1百k
1.圖片縮放
圖片縮放可使用convert命令
$in = 'a.png'; $out = 'a-convert-resize-100.png'; //$out = 'a.png'; replace the input infile //escapeshellarg可處理文件名中的特殊字符如空格 shell_exec('convert -resize 100 ' . escapeshellarg($in) . ' ' . escapeshellarg($out));
圖片從1850*983縮小到100*53(寬高比例不變)
2.圖片裁剪
圖片裁剪可使用php的imagecopy()或imagecrop()函數實現
$in = 'a.png'; $out = 'a-copy.png'; //裁剪寬度 $width = 100; //裁剪高度 $height = 80; //原圖的開始的x軸坐標 $x = 1; //原圖開始的y軸坐標 $y = 2; $inImage = imagecreatefrompng($in); //$inImage = imagecreatefromjpeg($in); $outImage = imagecreatetruecolor($width, $height); imagecopy($outImage, $inImage, 0, 0, $x, $y, $width, $height); imagepng($outImage, $out); //imagejpeg($outImage, $out); imagedestroy($inImage); imagedestroy($outImage);
3.圖片壓縮
jpg圖片可使用convert有損壓縮和jpegtran無損壓縮
convert –quality可將圖片按指定質量壓縮,但有時可能會越壓越大
jpegtran –progressive可將圖片壓縮為progressive圖片,就是加載時先模糊后清晰的那種圖,而不是從上到下顯示
$in = 'b.jpg'; $out = 'b-convert-quality-60.jpg'; $out2 = 'b-jpegtran-progressive.jpg'; $in = escapeshellarg($in); $out = escapeshellarg($out); $out2 = escapeshellarg($out2); shell_exec('convert -quality 60 ' . $in . ' ' . $out); shell_exec('jpegtran -copy none -optimize -progressive -outfile ' . $out2 . ' ' . $out);
png圖片可使用pngquant有損壓縮和optipng無損壓縮
pngquant可將png32或png24圖片壓縮為png8圖,仍保留了透明
pngquat –quality 設置過大經常會使圖片越壓越大,所以要小心設置,或不設置
$in = 'a.png'; $out = 'a-pngquant.png'; $out2 = 'a-pngquant-optipnt.png'; $in = escapeshellarg($in); $out = escapeshellarg($out); $out2 = escapeshellarg($out2); shell_exec('pngquant --speed 1 -o ' . $out . ' ' . $in); //replace file //shell_exec('pngquant --speed 1 -f --ext .png ' . $in); shell_exec('optipng -strip all -quiet -clobber -o3 -i0 ' . $out . ' -out ' . $out2);
4.先縮放還是先壓縮
好像先縮放后壓縮會更小(不一定准確,我只測了幾張圖,並且清晰度比較不了我的屏幕太模糊。。。)
下圖為a.png(1850*980)的測試數據
下圖為b.jpg(1920*1080)的測試數據
參考資料
Google優化圖片建議 https://developers.google.com/speed/docs/insights/OptimizeImages
攜程博客 http://ued.ctrip.com/blog/image-optimization-tools.html
imagemagic http://www.imagemagick.org/script/command-line-processing.php
jpegtran http://jpegclub.org/jpegtran/
optipng
pngquant