How does PHP dynamically crop pictures under Nginx

Source: Internet
Author: User

Previously wrote an article is also about the high-performance PHP picture dynamic cutting scheme, the article uses the Nginx cache and rewrite implementation, of course, coupled with the CDN, the solution has a problem is that the picture is not actually generated, but in the form of a binary cache. If the cache fails then you also need to request PHP to generate it again. If that's what I think of the difference.

The use of spare time, the new static generation of image support, support for the picture 3 mode switch, the portal site automatically cut the size of the picture, reduce the server bandwidth, image cropping using the Imagick component.

First, the idea of reconstruction: 1, write the request server to generate the picture dynamic script, the main thing is to compare the image to zoom calculation + cropping. 2. Determine the URL rules you want to generate, such as http://www.domain.com/www/300x200-1/test.jpg. 3, the browser to do cache processing. 4, the end.

Second, the PHP script to cut the picture dynamically

  1. /**

  2. * Author Pony_chiang
  3. * High-performance image cutting scheme
  4. * Requires Php-imagick extension
  5. */
  6. Ini_set ("Memory_limit", "80M");

  7. Request address such as http://yourdomain.com/resize.php?site=www&width=300&height=200&mode=2&path=uploadfile/ Helloworld.png

  8. Nginx rewrite rule rewrite ^ ([^\.] *)/s/(. *)/(\d+) x (\d+)-(\d)/(. *) $1/s/resize.php?site=$2&width=$3&height=$4&mode=$5&path=$6 last;

  9. $path = Trim ($_get [' path ']);

  10. $mode = Intval ($_get [' mode ']);
  11. $site = Trim ($_get [' site ']);
  12. $width = Intval ($_get [' width ']);
  13. $height = Intval ($_get [' height ']);

  14. $site _list = Array (' www ' = '/mnt/webroot/test/');

  15. $orig _dir = dirname (__file__);

  16. if (! array_key_exists ($site, $site _list)) {
  17. Header (' http/1.1-bad Request ');
  18. Exit ();
  19. }

  20. if ($mode > 3 | | $mode < 0) {

  21. Header (' http/1.1-bad Request ');
  22. Exit ();
  23. }

  24. $orig _file = $site _list [$site]. $path;

  25. if (! file_exists ($orig _file)) {
  26. Header (' http/1.1 404 Not Found ');
  27. Exit ();
  28. }

  29. $file _ext = '. '. PathInfo ($path, pathinfo_extension);

  30. $file _name = basename ($path, $file _ext);

  31. $save _path = "{$orig _dir}/{$site}/{$width}x{$height}-{$mode}/{$path}";
  32. $save _dir = dirname ($save _path);

  33. if (! file_exists ($save _dir))

  34. Wpx_mkdir ($save _dir);

  35. $target _width = $width;

  36. $target _height = $height;

  37. $new _width = $target _width;

  38. $new _height = $target _height;
  39. $image = new Imagick ($orig _file);
  40. List ($orig _width, $orig _height, $type, $attr) = getimagesize ($orig _file);

  41. if ($mode = = "0") {

  42. Equal to scaled image
  43. $new _height = $orig _height * $new _width/$orig _width;
  44. if ($new _height > $target _height) {
  45. $new _width = $orig _width * $target _height/$orig _height;
  46. $new _height = $target _height;
  47. }
  48. } else if ($mode = = "2") {
  49. Enlarge and crop an image
  50. $desired _aspect = $target _width/$target _height;
  51. $orig _aspect = $orig _width/$orig _height;

  52. if ($desired _aspect > $orig _aspect) {

  53. $trim = $orig _height-($orig _width/$desired _aspect);
  54. $image->cropimage ($orig _width, $orig _height-$trim, 0, $trim/2);
  55. Error_log ("HEIGHT TRIM $trim");
  56. } else {
  57. $trim = $orig _width-($orig _height * $desired _aspect);
  58. $image->cropimage ($orig _width-$trim, $orig _height, $trim/2, 0);
  59. } bbs.it-home.org
  60. }

  61. $image->resizeimage ($new _width, $new _height, Imagick::filter_lanczos, 1);

  62. $image->writeimage ($save _path);
  63. Header (' Content-type:image/jpeg ');
  64. Header (' last-modified: '. Gmdate (' d, D M Y h:i:s '). ' GMT ');
  65. Echo file_get_contents ($save _path);
  66. return true;

  67. Looping through the build directory

  68. function Wpx_mkdir ($dir, $mode = 0777) {
  69. if (Is_dir ($dir) | | @mkdir ($DIR, $mode))
  70. return true;
  71. if (! Wpx_mkdir (DirName ($dir), $mode))
  72. return false;
  73. Return @mkdir ($dir, $mode);
  74. }

Copy Code

Three, nginx.conf configuration

    1. server {

    2. Listen 80;
    3. server_name test.yourdomain.com;
    4. Root/mnt/webroot/test;
    5. Index index.php;
    6. Expires 30d;

    7. LOCATION/S {

    8. #只有当没有生成这张图片时才调用动态裁剪
    9. if (!-e $request _filename) {
    10. rewrite ^ ([^\.] *)/s/(. *)/(\d+) x (\d+)-(\d)/(. *) $1/s/resize.php?site=$2&width=$3&height=$4&mode=$5&path=$6 last;
    11. Break
    12. }
    13. }

    14. Error_page 404 403 402 502 503 504/404.html;

    15. Location =/404.html {
    16. }

    17. Location ~ \.php$ {

    18. Fastcgi_pass 127.0.0.1:9000;
    19. Fastcgi_index index.php;
    20. Fastcgi_param script_filename $document _root$fastcgi_script_name;
    21. Includefastcgi_params;
    22. }

    23. }

Copy Code

Note, highlighting the article about browser caching, whether it is generated by PHP or not, or using the Nginx cache generated images, add a line in the PHP code

    1. Header (' last-modified: '. Gmdate (' d, D M Y h:i:s '). ' GMT ');
Copy Code

It is a great help to use CDN. The first time the client accesses this file's HTTP status code is 200, after the refresh status code has been 304, understand the benefits of the local client cache, save bandwidth Oh.

  • Related Article

    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.