PHP plus nginx to implement dynamic cropping picture scheme

Source: Internet
Author: User
Tags crop image mkdir php code php script trim

  This article mainly introduces PHP plus nginx implementation of dynamic cropping picture scheme, using Imagick component implementation, need friends can refer to the following

Wrote a long time ago is also about high-performance PHP picture dynamic cropping scheme article, the article is used Nginx cache and rewrite implementation, of course, plus CDN, the solution exists a problem is that the picture is not actually generated, but in the form of a binary cache. If the cache fails then you will need to request PHP to generate it again. If I say the difference, I think for the moment. The use of free time, new static generated picture support, support to the picture 3 mode switch, in the portal automatically cut picture size, reduce server bandwidth, theoretically should also meet the needs of the business, the picture is cropped using the Imagick component.   A, the idea of reproduction: 1, first write a good request server to generate picture dynamic script, is mainly to the picture and so on than scaling calculation + cropping. 2, determine the URL rules you want to generate. 3, the browser do cache processing. 4, end. Second, dynamic cropping PHP script code as follows:/**  * Author Pony_chiang  * High performance image cropping scheme  * need php-imagick extension  */ini_set ("Memory_limi T "," 80M ");  //request address such as  helloworld.png//nginx rewrite rules  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 bad Request ');     exit (); }   if ($mode > 3 | | $mode < 0) {    header (' http/1.1 Request ');     exit ();}   $orig _file = $site _list [$site]. $path; if (! file_exists ($orig _file)) {    header (' http/1.1 404 Not Found ');     exit ();}   $fi Le_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") {   //Zoom image     $new _height = $orig _height * $new _width/$orig _width; &nbSp   if ($new _height > $target _height) {        $new _width = $orig _width * $target _height/$ori G_height;         $new _height = $target _height;    } else if ($mode = = "2") {   //zoom in and crop image     $desired _aspect = $target _width/$targe T_height;     $orig _aspect = $orig _width/$orig _height;       if ($desired _aspect > $orig _aspect) {        $trim = $orig _height-($orig _wi dth/$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);     & nbsp   $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;  //looping to generate directory function Wpx_mkdir ($dir, $mode = 0777) {    if (Is_dir ($dir) | | @mkdir ($DIR, $mode)) &NB Sp       return true;     if (! Wpx_mkdir (DirName ($dir), $mode))         return false;     return @mkdir ($dir, $mode); }     III, nginx.conf configuration   code is as follows: server {        Listen      ,   &N Bsp     server_name test.yourdomain.com;         root  /mnt/webroot/test;         Index  index.php;         expires 30d;           LOCATION/S {            #只有当没有生成这张图片时才调用动态裁剪   &NBS P        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;           &NBSP,         {          Error_page &NB Sp 404 403 402 502 503 504  /404.html;         location =/404.html {       }           Locati On ~. php$ {            Fastcgi_pass   127.0.0.1:9000         &NB Sp   Fastcgi_index  index.php;             Fastcgi_param  script_filename   $document _root$fastcgi_script_name ;             include        fastcgi_params;        }  }   PS: At the end of the article I would like to emphasize a little bit about browser caching articles, whether you are through phP-generated pictures, or using the Nginx cache generated pictures, add a line in the PHP code copy Code: Header (' last-modified: '. Gmdate (' d, D M Y h:i:s '). ' GMT '); It's very helpful for you to use CDN. The result is that the first time the client accesses this file, the HTTP status code is 200, and the status code is 304 after the refresh.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.