Nginx with PHP implementation to generate real-time thumbnail function _nginx

Source: Internet
Author: User
Tags save file

In doing automatic static, suddenly think of the following scenario, also gives the solution. Pro, really very practical, patience to look down.

When I upload a screenshot from the background, after the screenshot of 480*800, there is no small thumbnail of 320*480. OK, the server polls, all produce a 320*480 picture.

The next time, there are 160*240 pictures, and polling it, time-consuming and laborious, can not immediately get small map. This time, we will start to complain, how to have so many kinds of pictures ah, designers, you can not always think of what kind of pictures?

In fact, Nginx is a powerful reverse proxy server, through its rewrite module, we can implement the automatic generation of thumbnails, and do not have to poll the database. Product design, what size, the client directly through a certain rule of access is, I immediately produced to you.
And, when the background upload, just save a picture of the largest is OK.

In this case, you need other dimensions of the picture, just modify the client access mode.

Nginx Configuration:

Copy Code code as follows:

#假设, there is a file on the server: Abc.jpg, you can access the original image through Http://filefs.domain.com/file/abc.jpg. It is a real, we in the database also saved the "/file/abc.jpg" part of the content.
#现在, we want to implement this thumbnail by http://filefs.domain.com/file/abc.jpg.w320.jpg the #abc.jpg.w320.jpg (w320,320px width) automatically generated by the server. and return the picture data.
#要满足以下两个条件:
# 1. If abc.jpg.w320.jpg exists, do not recreate the picture
# 2. If not present, in the same request, return the picture data, and save the picture file to the server.


server {
Listen 80;
server_name filefs.domain.com;

root/var/www/http/filefs.domain.com;
Location/{
Index index.html index.htm;
}

Location ~ \. (png|jpg|jpeg|gif) $ {
#如果文件不存在, rewrite to the script file that generated the picture autoimg.php
if (!-f $request _filename) {
Rewrite ^/.*$/autoimg.php;
Expires Max;
}
#如果文件存在, set the expiration time, turn off the access log
if (-f $request _filename) {
Expires Max;
Access_log off;
}
}

Error_page 502 503 504/50x.html;
Location =/50x.html {
root/usr/share/nginx/html;
}

Location ~ autoimg.php$ {#安全性考虑, file server, only the scope of this script file is submitted to the PHP processing
Fastcgi_pass 127.0.0.1:9000;
Fastcgi_index index.php;
Fastcgi_param Script_filename/var/www/http/filefs.domain.com$fastcgi_script_name;
Include/usr/local/nginx/conf/fastcgi_params;
}
}

PHP produces picture file code:

Copy Code code as follows:

<?php
$file = $_server [' Request_uri '];//request string/file/abc.jpg.w320.jpg
$desfile = $_server [' Document_root ']. $file; Target Target Path/var/www/http/file/abc.jpg.w320.jpg
$dirname = DirName ($desfile). "/";
$filename = basename ($desfile);
if (Preg_match ()/([^\.] +\. (png|jpg|jpeg|gif)) \.W ([\d]+) \. (jpg)/i ", $filename, $m)) {
$srcfile = $dirname. $m [1];
$width = $m [3]; Match output file width
if (In_array ($width, Array (////Only 202 and 320-width files are generated)
202,
320
) && file_exists ($srcfile)) {//and the file does not exist
Thumbnail ($srcfile, $desfile, $width);
}
}

/**
* Generate thumbnails
*
* @param source $src
* @param-scaled broadband $width
*
*/
function thumbnail ($src, $des, $width) {
Ob_start ()//start intercepting output stream
$imageinfos = getimagesize ($SRC);
$ext = Strtolower (PathInfo ($SRC, 4));
if ($imageinfos [2] = = 1) {
$im = Imagecreatefromgif ($SRC);
} elseif ($imageinfos [2] = = 2) {
$im = Imagecreatefromjpeg ($SRC);
} elseif ($imageinfos [2] = = 3) {
$im = Imagecreatefrompng ($SRC);
}

if (Isset ($im)) {
$height = $imageinfos [1] * $width/$imageinfos [0];
$DST _img = Imagecreatetruecolor ($width, $height);

Imagesavealpha ($dst _img, true);
$trans _colour = Imagecolorallocatealpha ($dst _img, 0, 0, 0, 127);
Imagefill ($dst _img, 0, 0, $trans _colour);

Imagecopyresampled ($dst _img, $im, 0, 0, 0, 0, $width, $height, $imageinfos [0], $imageinfos [1]);

Header (' content-type:image/jpg ');
Imagejpeg ($DST _img, NULL, 90)//output file stream, 90--compression quality, 100 represents highest quality.

@imagedestroy ($im);
@imagedestroy ($dst _img);
} else {
echo @file_get_contents ($SRC);
}
$content = Ob_get_contents ();//Get output stream
Ob_end_flush ()//output stream to the Web page to ensure that the first request also has picture data back
@file_put_contents ($des, $content);//Save File
}
?>

Effect Chart:

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.