PHP加Nginx实现动态裁剪图片方案


Posted in PHP onMarch 10, 2014

许久以前写过一篇也是关于高性能PHP图片动态裁剪方案的文章,那文章使用的是nginx Cache和rewrite实现的,当然再加上CDN,那个方案存在一个问题就是图片并没有实际生成,而是以二进制的形式存在缓存中。如果缓存失效了那么还需要请求php再次生成。如果说到区别这是我暂且认为的吧。
利用空余时间,新增了静态生成图片支持,支持对图片3种模式切换,在门户网站自动对图片尺寸进行裁剪,减少服务器带宽,理论上应该也满足了业务的需求吧,图片裁剪使用了Imagick组件。

一、思路再现:
1、先写好请求服务器生成图片动态脚本,主要就是对图片进行等比缩放计算+裁剪。
2、确定你想要生成的url规则,比如http://www.domain.com/www/300×200-1/test.jpg。
3、对浏览器做缓存处理。
4、结束。
二、动态裁剪PHP脚本

/**
 * Author pony_chiang
 * 高性能图像裁剪方案
 * 需要php-imagick扩展
 */
ini_set ( "memory_limit", "80M" );// 请求地址比如  http://yourdomain.com/resize.php?site=www&width=300&height=200&mode=2&path=uploadfile/helloworld.png
// nginx重写规则  rewrite ^([^\.]*)/s/(.*)/(\d+)x(\d+)-(\d)/(.*) $1/s/resize.php?site=$2&width=$3&height=$4&mode=$5&path=$6 last;
$path = trim ( $_GET ['path'] );
$mode = intval ( $_GET ['mode'] );
$site = trim ( $_GET ['site'] );
$width = intval ( $_GET ['width'] );
$height = intval ( $_GET ['height'] );
$site_list = array ('www' => '/mnt/webroot/test/' );
$orig_dir = dirname ( __FILE__ );
if (! array_key_exists ( $site, $site_list )) {
    header ( 'HTTP/1.1 400 Bad Request' );
    exit ();
}
if ($mode > 3 || $mode < 0) {
    header ( 'HTTP/1.1 400 Bad Request' );
    exit ();
}
$orig_file = $site_list [$site] . $path;
if (! file_exists ( $orig_file )) {
    header ( 'HTTP/1.1 404 Not Found' );
    exit ();
}
$file_ext = '.' . pathinfo ( $path, PATHINFO_EXTENSION );
$file_name = basename ( $path, $file_ext );
$save_path = "{$orig_dir}/{$site}/{$width}x{$height}-{$mode}/{$path}";
$save_dir = dirname ( $save_path );
if (! file_exists ( $save_dir ))
    wpx_mkdir ( $save_dir );
$target_width = $width;
$target_height = $height;
$new_width = $target_width;
$new_height = $target_height;
$image = new Imagick ( $orig_file );
list ( $orig_width, $orig_height, $type, $attr ) = getimagesize ( $orig_file );
if ($mode == "0") {
    //等比缩放图像
    $new_height = $orig_height * $new_width / $orig_width;
    if ($new_height > $target_height) {
        $new_width = $orig_width * $target_height / $orig_height;
        $new_height = $target_height;
    }
} else if ($mode == "2") {
    // 放大并裁剪图像
    $desired_aspect = $target_width / $target_height;
    $orig_aspect = $orig_width / $orig_height;
    if ($desired_aspect > $orig_aspect) {
        $trim = $orig_height - ($orig_width / $desired_aspect);
        $image->cropImage ( $orig_width, $orig_height - $trim, 0, $trim / 2 );
        error_log ( "HEIGHT TRIM $trim" );
    } else {
        $trim = $orig_width - ($orig_height * $desired_aspect);
        $image->cropImage ( $orig_width - $trim, $orig_height, $trim / 2, 0 );
    }
}
$image->resizeImage ( $new_width, $new_height, imagick::FILTER_LANCZOS, 1 );
$image->writeImage ( $save_path );
header ( 'Content-Type: image/jpeg' );
header ( 'Last-Modified: ' . gmdate ( 'D, d M Y H:i:s' ) . ' GMT' );
echo file_get_contents ( $save_path );
return true;
// 循环生成目录
function wpx_mkdir($dir, $mode = 0777) {
    if (is_dir ( $dir ) || @mkdir ( $dir, $mode ))
        return true;
    if (! wpx_mkdir ( dirname ( $dir ), $mode ))
        return false;
    return @mkdir ( $dir, $mode );
}

三、nginx.conf配置

server {
        listen       80;
        server_name test.yourdomain.com;
        root   /mnt/webroot/test;
        index  index.php;
        expires 30d;        location /s {
           #只有当没有生成这张图片时才调用动态裁剪
           if (!-e $request_filename) {
             rewrite ^([^\.]*)/s/(.*)/(\d+)x(\d+)-(\d)/(.*) $1/s/resize.php?site=$2&width=$3&height=$4&mode=$5&path=$6 last;
             break;
           }
        }
        error_page   404 403 402 500 502 503 504  /404.html;
        location = /404.html {
        }
        location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
}

PS:在文章的末尾我要特别强调一点是关于浏览器缓存的文章,不管你是否是通过php生成的图片也好,还是使用nginx缓存生成的图片也罢,在php代码中添加一行
header('Last-Modified: ' .gmdate('D, d M Y H:i:s') . ' GMT' );

对你使用CDN有十分莫大的帮助。具体产生的效果就是客户端第一次访问此文件的http状态码是200,刷新后状态码一直都是304了。
PHP 相关文章推荐
常用的php ADODB使用方法集锦
Mar 25 PHP
简单的PHP多图上传小程序代码
Jul 17 PHP
php数组函数序列之array_push() 数组尾部添加一个或多个元素(入栈),返回新长度。
Nov 07 PHP
php中自定义函数dump查看数组信息类似var_dump
Jan 27 PHP
PHP中isset()和unset()函数的用法小结
Mar 11 PHP
CI框架学习笔记(一) - 环境安装、基本术语和框架流程
Oct 26 PHP
PHP连接MySQL数据的操作要点
Mar 20 PHP
如何判断php mysqli扩展类是否开启
Dec 24 PHP
PHP+JS实现的实时搜索提示功能
Mar 13 PHP
PHP实现用户异地登录提醒功能的方法【基于thinkPHP框架】
Mar 15 PHP
CI框架教程之优化验证码机制详解【验证码辅助函数】
Apr 16 PHP
laravel-admin的图片删除实例
Sep 30 PHP
php实现文件下载简单示例(代码实现文件下载)
Mar 10 #PHP
php实现文件编码批量转换
Mar 10 #PHP
php导出word文档与excel电子表格的简单示例代码
Mar 08 #PHP
php 创建以UNIX时间戳命名的文件夹(示例代码)
Mar 08 #PHP
PHP_Cooikes不同页面无法传递的解决方法
Mar 07 #PHP
php function用法如何递归及return和echo区别
Mar 07 #PHP
详解PHP中strlen和mb_strlen函数的区别
Mar 07 #PHP
You might like
处理php自动反斜杠的函数代码
2010/01/05 PHP
php读取文件内容至字符串中,同时去除换行、空行、行首行尾空格(Zjmainstay原创)
2012/07/31 PHP
php过滤html中的其他网站链接的方法(域名白名单功能)
2014/04/24 PHP
PHPMailer发送邮件
2016/12/28 PHP
thinkPHP实现的省市区三级联动功能示例
2017/05/05 PHP
CodeIgniter整合Smarty的方法详解
2017/08/25 PHP
修复bash漏洞的shell脚本分享
2014/12/31 Javascript
jQuery实现连续动画效果实例分析
2015/10/09 Javascript
分享网页检测摇一摇实例代码
2016/01/14 Javascript
JS 全屏和退出全屏详解及实例代码
2016/11/07 Javascript
WebView启动支付宝客户端支付失败的问题小结
2017/01/11 Javascript
一个可复用的vue分页组件
2017/05/15 Javascript
vue项目webpack中Npm传递参数配置不同域名接口
2018/06/15 Javascript
JS判断两个数组或对象是否相同的方法示例
2019/02/28 Javascript
vue中实现动态生成二维码的方法
2020/02/21 Javascript
JS求解两数之和算法详解
2020/04/28 Javascript
React实现轮播效果
2020/08/25 Javascript
JavaScript常用工具函数汇总(浏览器环境)
2020/09/17 Javascript
Python中使用wxPython开发的一个简易笔记本程序实例
2015/02/08 Python
Python爬取京东的商品分类与链接
2016/08/26 Python
利用Python实现颜色色值转换的小工具
2016/10/27 Python
python交互式图形编程实例(二)
2017/11/17 Python
python smtplib模块自动收发邮件功能(二)
2018/05/22 Python
Python使用pickle模块实现序列化功能示例
2018/07/13 Python
Django组件cookie与session的具体使用
2019/06/05 Python
python 读写excel文件操作示例【附源码下载】
2019/06/19 Python
pymysql 插入数据 转义处理方式
2020/03/02 Python
用HTML5制作烟火效果的教程
2015/05/12 HTML / CSS
高级运动鞋:GREATS
2019/07/19 全球购物
家乐福台湾线上购物网:Carrefour台湾
2020/09/15 全球购物
环保倡议书50字
2014/05/15 职场文书
学习型班组申报材料
2014/05/31 职场文书
党员志愿者活动方案
2014/08/28 职场文书
违规违纪检讨书范文
2015/05/06 职场文书
运动会加油稿30字
2015/07/21 职场文书
财务人员入职担保书
2015/09/22 职场文书