安装JPG,PNG开发包
apt-get install libjpeg62-dev libpng12-dev libtiff4-dev
安装ImageMagick和imagick
- tar zxvf ImageMagick.tar.gz
- cd ImageMagick-6.5.1-2/
- ./configure
- make
- make install
- cd ../
- tar zxvf imagick-2.3.0.tgz
- cd imagick-2.3.0/
- /usr/local/webserver/php/bin/phpize
- ./configure --with-php-config=/usr/local/webserver/php/bin/php-config
- make
- make install
- cd ../
如果:no decode delegate for this image format
安装:apt-get install libjpeg62-dev libpng12-dev libtiff4-dev后再重新安装ImageMagick和imagick
如果:libMagickCore.so.5: cannot open shared object file
执行命令:ldconfig /usr/local/lib
修改php.ini
extension = "imagick.so"
重启php-fpm
/etc/init.d/php5-fpm restart
增加rewrite
rewrite ^/uploads/(.*)\.(.*)$ /img.php last;
重启nignx
nginx -s reload
增加img.php代码处理
- <?php
- /*
- A thumbnail creation.
- */
- /* Create the Imagick object */
- $img = $_SERVER['REQUEST_URI'];
- define('DEDEROOT', str_replace("\\", '/', dirname(__FILE__) ) );
- preg_match("/(.*)_(\d+)_(\d+)\.(\w+)/is",$img,$match);
- $getWidth = $match[2];
- $getHeight = $match[3];
- $normalImg = DEDEROOT. $match[1].".".$match[4];
- $smallImg = DEDEROOT. $match[0];
- $im = new Imagick();
- if (!$match[4] || !file_exists($normalImg)) {
- $normalImg = DEDEROOT. $img;
- if (!file_exists($normalImg)) {
- //没有图片
- header("HTTP/1.1 404 Not Found");
- exit;
- }
- //使用原图
- $im->readImage( $normalImg);
- header( "Content-Type: image/{$im->getImageFormat()}" );
- echo $im->getImageBlob();
- $im->destroy();
- exit;
- }
- /* Read the image file */
- $im->readImage( $normalImg);
- if ($getWidth && $getHeight) {
- $srcWH = $im->getImageGeometry();
- $rate_w = $getWidth / $srcWH['width'];
- $rate_h = $getHeight / $srcWH['height'];
- $rate = ($rate_w > $rate_h) ? $rate_w : $rate_h;
- $rate = $rate > 1 ? 1 : $rate;
- $thumb_w = round($srcWH['width'] * $rate);
- $thumb_h = round($srcWH['height'] * $rate);
- //缩略
- $im->thumbnailImage( $thumb_w, $thumb_h );
- if ($thumb_w>$getWidth || $thumb_h>$getHeight) {
- $fromX = ($thumb_w-$getWidth)/2;
- //剪切
- $im->cropImage($getWidth, $getHeight,$fromX,0);
- }
- } elseif ($getWidth && !$getHeight) {
- $im->thumbnailImage( $getWidth, null);
- } elseif (!$getWidth && $getHeight) {
- $im->thumbnailImage(null, $getHeight );
- }
- /* Write the thumbail to disk */
- $im->writeImage($smallImg);
- header( "Content-Type: image/{$im->getImageFormat()}" );
- echo $im->getImageBlob();
- /* Free resources associated to the Imagick object */
- $im->destroy();
- ?>
优化:
nginx的rewrite时可以做个判断,如果已经有生成的图片则直接显示。不用再到php里处理。
if (!-f $request_filename) {
rewrite ^/uploads/(.*)\.(.*)$ /img.php last;
}
参考:
http://www.digitalsanctum.com/2009/03/18/installing-imagemagick-from-source-on-ubuntu-804/
http://bootpolish.net/home_howto_installimagemagick
http://wenku.baidu.com/view/2e93f278168884868762d689.html
http://apps.hi.baidu.com/share/detail/37348887
http://hi.baidu.com/houwenbin1986/blog/item/a0afa1fa3adcad294e4aea48.html
http://www.zhouchen33.com/index.php/archives/284