PHP图片缩放,裁剪和压缩

Google PageSpeed Insights能够对网页加载速度评分,并给出优化建议php

简单来讲,优化图片即便用合适尺寸的图片(缩放,裁剪),压缩图片html

这里只介绍jpng和png两种图片格式shell

软件准备:

imagemagick函数

apt-get install imagemagick

jpegtran测试

apt-get install libjpeg-turbo-progs

optipng优化

apt-get install optipng

pngquantui

apt-get install pngquant

php5-gdgoogle

apt-get install php5-gd

0.格式转换

通常来讲,jpg图片比png图片小得多,如无特殊需求(如透明)使用jpg图片可大大减少图片大小3d

格式转换可以使用convert命令htm

shell_exec('convert a.png a.jpg');

图片从7百k变成了1百k

jpg

 

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(宽高比例不变)

convert_resize

 

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);

jpg-comopress

 

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);

png-compress

 

4.先缩放仍是先压缩

好像先缩放后压缩会更小(不必定准确,我只测了几张图,而且清晰度比较不了个人屏幕太模糊。。。)

下图为a.png(1850*980)的测试数据

apng

下图为b.jpg(1920*1080)的测试数据

ajpg

 

参考资料

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