


Detailed explanation of the steps to dynamically crop images using PHP in nginx
这次给大家带来nginx内php动态裁剪图片步骤详解,nginx内php动态裁剪图片的注意事项有哪些,下面就是实战案例,一起来看一下。
以前写过一篇也是关于高性能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 ); } www.jbxue.com } $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; includefastcgi_params; } }
说明,强调下关于浏览器缓存的文章,不管是否是通过php生成的图片也好,还是使用nginx缓存生成的图片也罢,在php代码中添加一行
header('Last-Modified: ' .gmdate('D, d M Y H:i:s') . ' GMT' );
对使用CDN有莫大的帮助。
客户端第一次访问此文件的http状态码是200,刷新后状态码一直都是304了,明白其中的好处了,本地客户端缓存了,节省带宽哦。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of the steps to dynamically crop images using PHP in nginx. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

How to configure an Nginx domain name on a cloud server: Create an A record pointing to the public IP address of the cloud server. Add virtual host blocks in the Nginx configuration file, specifying the listening port, domain name, and website root directory. Restart Nginx to apply the changes. Access the domain name test configuration. Other notes: Install the SSL certificate to enable HTTPS, ensure that the firewall allows port 80 traffic, and wait for DNS resolution to take effect.

The methods that can query the Nginx version are: use the nginx -v command; view the version directive in the nginx.conf file; open the Nginx error page and view the page title.

Starting an Nginx server requires different steps according to different operating systems: Linux/Unix system: Install the Nginx package (for example, using apt-get or yum). Use systemctl to start an Nginx service (for example, sudo systemctl start nginx). Windows system: Download and install Windows binary files. Start Nginx using the nginx.exe executable (for example, nginx.exe -c conf\nginx.conf). No matter which operating system you use, you can access the server IP

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.
