Home  >  Article  >  Backend Development  >  PHP plus Nginx to implement dynamic cropping image solution_PHP tutorial

PHP plus Nginx to implement dynamic cropping image solution_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:36:191039browse

A long time ago I wrote an article about a high-performance PHP image dynamic cropping solution. That article was implemented using nginx Cache and rewrite. Of course, coupled with CDN, one problem with that solution was that the image was not actually generated. , but is stored in the cache in binary form. If the cache fails, you need to request php to generate it again. As for the difference, this is what I think for the time being.
Using spare time, we have added support for statically generated images, which supports switching between 3 image modes. It can automatically crop the image size on the portal website and reduce server bandwidth. In theory, it should also meet the needs of the business. Image cropping Used Imagick component.

1. Reproduction of ideas:
1. First write a dynamic script that requests the server to generate a picture, which mainly performs proportional scaling calculation + cropping of the picture.
2. Determine the url rule you want to generate, such as http://www.domain.com/www/300×200-1/test.jpg.
3. Caching the browser.
4. End.
2. Dynamic cropping PHP script

Copy code The code is as follows:

/**
* Author pony_chiang
* High-performance image cropping solution
* Requires php-imagick extension
*/
ini_set ( "memory_limit", "80M" );

// Request address such as http://yourdomain.com/resize.php?site=www&width=300&height=200&mode=2&path=uploadfile/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 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") {
//Constantly scaled image
$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") {
// Enlarge and crop the image
$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 ); >        $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;

// Loop to generate directory
function wpx_mkdir($dir, $mode = 0777) {
if (is_dir ( $dir ) || @mkdir ( $dir, $mode = 0777) ))
return true;
if (! wpx_mkdir ( dirname ( $dir ), $mode ))
return false;
return @mkdir ( $dir, $mode );
}

3. nginx.conf configuration

Copy code The code is as follows:

server {
listen 80;
server_name test.yourdomain.com;
root /mnt/webroot/test;
index index.php;
expires 30d;

location /s {
​​ #Only when Dynamic cropping is called only when this picture is not generated. (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: In the article At the end, I want to emphasize one point in particular about the article about browser caching. Whether you generate images through php or use nginx cache, add a line


to the php code.
Copy code

The code is as follows:
header('Last-Modified: ' .gmdate('D, d M Y H:i:s') . ' GMT' );It will be very helpful for you to use CDN. The specific effect is that the http status code when the client accesses this file for the first time is 200. After refreshing, the status code is always 304.
http://www.bkjia.com/PHPjc/739780.html
www.bkjia.com

true

TechArticleA long time ago I wrote an article about a high-performance PHP image dynamic cropping solution. That article used nginx Cache and rewrite are implemented, of course plus CDN, there is a solution for that...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn