许久以前写过一篇也是关于高性能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加Nginx实现动态裁剪图片方案的更多相关文章

  1. 如何兼容所有Android版本选择照片或拍照然后裁剪图片--基于FileProvider和动态权限的实现

    我们知道, Android操作系统一直在进化. 虽然说系统是越来越安全, 可靠, 但是对于开发者而言, 开发难度是越来越大的, 需要注意的兼容性问题, 也越来越多. 就比如在Android平台上拍照或 ...

  2. Upsync:微博开源基于Nginx容器动态流量管理方案

    Upsync:微博开源基于Nginx容器动态流量管理方案 https://mp.weixin.qq.com/s?__biz=MzAwMDU1MTE1OQ==&mid=404151075& ...

  3. nginx/iptables动态IP黑白名单实现方案

    nginx/iptables动态IP黑白名单实现方案 一.手动封IP步骤 1.Nginx手动封IP 1.获取各个IP访问次数 awk '{print $1}' nginx.access.log |so ...

  4. 基于 OpenResty 的动态服务路由方案

    2019 年 5 月 11 日,OpenResty 社区联合又拍云,举办 OpenResty × Open Talk 全国巡回沙龙武汉站,又拍云首席布道师在活动上做了< 基于 OpenResty ...

  5. android 开发 实现一个进入相机拍照后裁剪图片或者进入相册选中裁剪图片的功能

    实现思维路径: 以进入相机拍照的思维路线为例子: 1.进入app 2.判断之前是否保存头像,如果有就显示历史图像 (下面代码中在getOldAvatar();方法中执行这个逻辑) 3.点击更换图像的B ...

  6. 《nginx 三》实现nginx的动态负载均衡——实战

    Http动态负载均衡 什么是动态负载均衡 传统的负载均衡,如果Upstream参数发生变化,每次都需要重新加载nginx.conf文件, 因此扩展性不是很高,所以我们可以采用动态负载均衡,实现Upst ...

  7. vue-cli3项目中解决动态引入图片img404的问题

    博主最近手头再做一个项目,需要调用天气接口,并且还要动态显示天气相关图片icon. 本来以为没什么大问题,结果硬生生被这个动态图片路径搞得民不聊生(博主还是 too young,too simple~ ...

  8. 【Nginx】基于Consul+Upsync+Nginx实现动态负载均衡

    一.Http动态负载均衡 什么是动态负载均衡 动态负载均衡实现方案 常用服务器注册与发现框架 二.Consul快速入门 Consul环境搭建 三.nginx-upsync-module nginx-u ...

  9. 通过php安装Imagick扩展给动态gif图片打水印

    通过php安装Imagick扩展给动态gif图片打水印 一直以来php处理图片都是以gd为主流,直到近些年Imagick的使用才渐渐变多. gd通常用来缩放图片,给图片打水印等基本功能,对于复杂效果如 ...

随机推荐

  1. windows内核实现的34个关键问题

    http://book.kongfz.com/237217/670391178/#bookComm

  2. SQLITE3 --详解

    由于我主要负责我们小组项目数据库模块的部分所以这几天都一直在研究在iphone中最为常用的一个简单数据库sqlite,自己也搜集很多资料,因此在 这里总结一下这几天的学习成果: Sqlite 操作简明 ...

  3. 【hibernate】主键生成策略使用UUID报出如下警告:org.hibernate.id.UUIDHexGenerator - HHH000409: Using org.hibernate.id.UUIDHexGenerator which does not generate IETF RFC 4122 compliant UUID values;

    主键生成策略使用UUID报出如警告如下: 控制台- 2017-11-24 18:40:14 [restartedMain] WARN org.hibernate.id.UUIDHexGenerator ...

  4. PS中把图片白色背景变成透明的方法

    用魔术橡皮擦擦去白色(调整容差,取消连续,点选白色部分),保存成png格式

  5. Flutter开发记录part1

    (1)AppBar:automaticallyImplyLeading//是否带返回leading箭头 (2)非route路由页面跳转 :Navigator.of(context).push(Mate ...

  6. python核心编程学习(第三版)之字符串匹配

    表示择一匹配的管道符号|,表示一个“从多个模式中选中其一”,有时候也称作并或者逻辑或 点号或者句号.符号匹配出了换行符\n以外的任何字符.如果要匹配句号,只需要使用反斜线转移句号符号的功能. ^匹配字 ...

  7. OllyDbg 使用笔记 (一)

    OllyDbg 使用笔记 (一) 參考 书:<加密与解密> 视频:小甲鱼 解密系列 视频 ollydbg下载地址:http://tools.pediy.com/debuggers.htm ...

  8. http Keep-Alive

    1.什么是Keep-Alive模式? 我们知道HTTP协议采用“请求-应答”模式,当使用普通模式,即非KeepAlive模式时,每个请求/应答客户和服务器都要新建一个连接,完成之后立即断开连接(HTT ...

  9. vue2.X 自定义 侧滑菜单 组件

    1.vue2.0 封装 侧滑菜单组件 Sidebar.vue <!-- 侧滑菜单 组件 --> <template> <div> <transition na ...

  10. boost库shared_ptr实现桥接模式

    主程序 /*将抽象部分与实现部分分离,使它们都能够独立的变化*/ #include "bridge.h" int main() { cout <<"main ...