PHP image auto crop to cope with display of different sizes _ PHP

Source: Internet
Author: User
Tags imagejpeg
An image may be displayed in different places, with different sizes and proportions. Therefore, it is useful to automatically crop the image in this example, if you have any requirement, you can check out the portal site. you must know that an image may be displayed in different places, with different sizes and proportions,
If you only use one graph, it will definitely be distorted, and it will be too wasteful to link the large graph in the area where the small graph is displayed ..... processing with thumbnails is not perfect, because the proportions and sizes of each place may be different. for example!

See.

In this place, a list is actually called, but the size of the image is different. How Wide and Narrow Are There? what should you do when such a situation occurs, if you use the original address directly, it will be distorted. if you do not have a thumbnail, it will be automatically adjusted. you do not know how wide or high the image requires,
Bytes ------------------------------------------------------------------------------------------------------------------
Enter the subject below:

I have been using one method, that is, PHP automatic cropping... you have seen similar image addresses/aaaa/abc_200_100.jpg or/aaaa/abc_200 * 100.jpg.
My approach is to convert the image address to an address similar to the one above, and then redirect it to a processing program through apache rewrite. generate an image based on the width and height and save it,

There are several advantages:

First, it is very flexible. you can control the width and height of images without deformation, and the program will always display the most picture content.
Second, when the image is generated once, apache will not redirect to the program next time, because there is a rule before it! D! F this judgment means that the current file will be directed only when it does not exist. The next time the image exists, it will not come out again and it will be a real image.

The bad thing is that the generated images may be large and the occupied space is large, but it doesn't matter if it is your own server.

Okay. let's take discuz as an example.

The code is as follows:


Function crop_img ($ img, $ width = 200, $ height = 200 ){
$ Img_info = parse_url ($ img );
/* The external link directly returns the image address */
If (! Empty ($ img_info ['host']) & $ img_info ['host']! = $ _ SERVER ['http _ host']) {
Return $ img;
} Else {
$ Pos = strrpos ($ img ,'.');
$ Img = substr ($ img, 0, $ pos). '_'. $ width. '_'. $ height. substr ($ img, $ pos );
Return $ img;
}
}

Function img ($ img, $ width, $ height ){
$ Img_info = parse_url ($ img );
/* The external link directly returns the image address */
If (! Empty ($ img_info ['host']) & $ img_info ['host']! = $ _ SERVER ['http _ host']) {
Return $ img;
} Else {
$ Pos = strrpos ($ img ,'.');
$ Img = substr ($ img, 0, $ pos). '_'. $ width. '_'. $ height. substr ($ img, $ pos );
Echo '';
Return;
}
}


Function usage: crop_img ('source Image address', 'width', and 'height'); this function returns the processed image address. the img function returns the image tag string directly, for example, call this function in the discuz Template {eval img ($ pic, 200,100 )}
In this case, the returned address is/data/attachment/forum/aaaaaa_200_100.jpg. Currently, this image does not exist. see Step 2.

Step 2 add apache rewrite rules

The code is as follows:



RewriteEngine on


RewriteCond % {REQUEST_FILENAME }! -D
RewriteCond % {REQUEST_FILENAME }! -F
RewriteRule ^ data/attachment/(. *) $ images. php? Url = $1 [L]



The above means that all files that do not exist at the beginning of data/attachement/address are directed to image. php for processing, and the url is transmitted as a parameter.

The third part is the code in image. php.

The code is as follows:


<? Php

$ Url = $ _ GET ['URL'];
$ Src = './data/attachment/'. preg_replace ('/_ (\ d +)/', '', $ url );
$ Filename = './data/attachment/'. $ url;

If (file_exists ($ filename )){
Ob_start ();
Header ('content-type: image/jpeg ');
Readfile ($ filename );
Ob_flush ();
Flush ();
} Else {
If (! Preg_match ('/_ (\ d +)/', $ url, $ wh )){
Defulat ();
Exit ();
}
$ Width = $ wh [1];
$ Height = $ wh [2];
Thumb (realpath ($ src), $ width, $ height, $ filename, 'crop', '85 ');
}

Function thumb ($ src, $ width, $ height, $ filename, $ mode = 'scale', $ quality = '000000 '){
Try {
$ ImageValue = getimagesize ($ src );
$ SourceWidth = $ imageValue [0]; // source image width
$ SourceHeight = $ imageValue [1]; // original image height
$ ThumbWidth = $ width; // Thumbnail width
$ ThumbHeight = $ height; // The height of the thumbnail.
$ _ X = 0;
$ _ Y = 0;
$ W = $ sourceWidth;
$ H = $ sourceHeight;
If ($ mode = 'scale '){
If ($ sourceWidth <= $ thumbWidth & $ sourceHeight <= $ thumbHeight ){
$ _ X = floor ($ thumbWidth-$ sourceWidth)/2 );
$ _ Y = floor ($ thumbHeight-$ sourceHeight)/2 );
$ ThumbWidth = $ sourceWidth;
$ ThumbHeight = $ sourceHeight;
} Else {
If ($ thumbHeight * $ sourceWidth> $ thumbWidth * $ sourceHeight ){
$ ThumbHeight = floor ($ sourceHeight * $ width/$ sourceWidth );
$ _ Y = floor ($ height-$ thumbHeight)/2 );
} Else {
$ ThumbWidth = floor ($ sourceWidth * $ height/$ sourceHeight );
$ _ X = floor ($ width-$ thumbWidth)/2 );
}
}
} Else if ($ mode = 'crop '){
If ($ sourceHeight <$ thumbHeight) {// if the source image size is smaller than the current size
$ ThumbWidth = floor ($ thumbWidth * $ sourceHeight/$ thumbHeight );
$ ThumbHeight = $ sourceHeight;
}
If ($ sourceWidth <$ thumbWidth ){
$ ThumbHeight = floor ($ thumbHeight * $ sourceWidth/$ thumbWidth );
$ ThumbWidth = $ sourceWidth;
}

$ S1 = $ sourceWidth/$ sourceHeight; // original image ratio
$ S2 = $ width/$ height; // ratio of the new graph
If ($ s1 ==$ s2 ){

} Else if ($ s1> $ s2) {// full height
$ Y = 0;
$ Ax = floor ($ sourceWidth * ($ thumbHeight/$ sourceHeight ));
$ X = ($ ax-$ thumbWidth)/2;
$ W = $ thumbWidth/($ thumbHeight/$ sourceHeight );

} Else {// Full width
$ X = 0;
$ Ay = floor ($ sourceHeight * ($ thumbWidth/$ sourceWidth); // simulate the original image proportional height
$ Y = ($ ay-$ thumbHeight)/2;
$ H = $ thumbHeight/($ thumbWidth/$ sourceWidth );
}

}
Switch ($ imageValue [2]) {
Case 2: $ source = imagecreatefromjpeg ($ src );
Break;
Case 1: $ source = imagecreatefromgif ($ src );
Break;
Case 3: $ source = imagecreatefrompng ($ src );
Break;
Case 6: $ source = imagecreatefromwbmp ($ src );
Break;
Default: defulat ();
Return;
}
Header ("Content-type: image/jpeg ");
$ Thumb = imagecreatetruecolor ($ width, $ height );
Imagefill ($ thumb, 0, 0, imagecolorallocate ($ thumb, 255,255,255 ));
Imagecopyresampled ($ thumb, $ source, 0, 0, $ x, $ y, $ width, $ height, $ w, $ h );
Imagejpeg ($ thumb, null, $ quality );
// If ($ _ SERVER ['http _ referer'] | false! = Stripos ($ _ SERVER ['http _ referer'], 'http: // '. $ _ SERVER ['server _ name']) {
Imagejpeg ($ thumb, $ filename, $ quality );
//}
Imagedestroy ($ thumb );
Imagedestroy ($ source );
} Catch (Exception $ ex ){
Defulat ();
}
}

Function defulat (){
$ Default_img = realpath ('media/images/nopic.jpg ');
Ob_start ();
Header ('content-type: image/jpeg ');
Readfile ($ default_img );
Ob_flush ();
Flush ();
}


The thumb function can control the cropping mode. scale is proportional scaling without cropping. if it is not enough, it is white and crop is cropping. if the required aspect ratio is greater than the aspect ratio of the source image, the maximum display width is maintained, and the upper and lower part of the center cropping is required. If the width to height ratio is smaller than the original image width to height, the maximum height is maintained. the left and right parts of the center are cut. In short, scale down the image without deformation and retain the maximum image content. haha how embarrassing this code is. try it out. of course, you need to support rewrite and GD2.
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.