Automatic cutting of PHP picture to cope with the display of different sizes

Source: Internet
Author: User
Tags flush imagejpeg readfile

If you have been a friend of that kind of portal, you must know that a picture may be displayed in different places, sizes and proportions.

If only using a picture, then will certainly deformation, and in the display of small map, link large map, and too wasteful ... Using thumbnails to deal with is not perfect, because the proportions of each place may not be the same size, for example!


Please see the picture.

In this place, in fact the tune out is a list, but the size of the picture is not the same, there is much wider and narrower, when encountered such a situation when you do it, if the direct use of the original address, will certainly be deformed, if the thumbnail is not reliable, this transfer is automatically transferred, You don't even know which picture needs to be big and wide,
--------------------------------------------------------------------------------------------------------------- ---
Let's get down to business:

I always use one method, that is, PHP automatic cutting ... You've seen a picture address like that,/aaaa/abc_200_100.jpg or/aaaa/abc_200*100.jpg.
My way is to translate this image address into a similar address, and then go through Apache's rewrite to a handler. Generate a picture from the height and then save it,

There are several advantages to doing so:

First, very flexible, where there are pictures, you need to be how wide and how high, you can control, will not deform, and the program will always let the picture content display the most
Second one, when the picture is generated once, Apache will not be redirected to the program next time, because in front of the rule there is!d!f this judgment, meaning that the current file does not exist when it will be directed away, the next time the picture exists, it will not come out directly is really the picture

The bad place is that the resulting picture may be more, occupy the space is also relatively large, but if it is their own server that does not matter, can be sorted out

OK, we'll take discuz as an example.

The

code is as follows:


function crop_img ($img, $width =, $height = 200) {


$img _info = Parse_url ($img);


/* External link directly back to the picture 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);


/* External link directly back to the picture 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 ' <img src= '. $img. ' width= '. $width. ' height= '. $height. '/> ';


return;


}


}


The use of the function crop_img (' original address ', ' width ', ' height '); This function returns the address of the processed image, and the IMG function returns the image tag string directly, such as calling this function in the discuz template {eval img ($pic, 200,100)}
So the return address is/data/attachment/forum/aaaaaa_200_100.jpg. Now the picture is not there. Look at the second step

The second step is to add Apache rewrite rules

The

code is as follows:


<ifmodule mod_rewrite.c>


Rewriteengine on








Rewritecond%{request_filename}!-d


Rewritecond%{request_filename}!-f


rewriterule ^data/attachment/(. *) $ images.php?url=$1 [L]





</IfModule>


The above meaning, is data/attachement/this address does not exist at the beginning of the file are directed to the image.php to handle, and the URL when the parameters passed

The third part is image.php, the inside code.

The

code is as follows:


<?php





$url = $_get[' url '];


$src = './data/attachment/'. Preg_replace ('/_ (d+) _ (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+) _ (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 = ' 100 ') {


try {


$imageValue = getimagesize ($SRC);


$sourceWidth = $imageValue [0]; Wide
of original artwork

$sourceHeight = $imageValue [1]; Original High


$thumbWidth = $width; Thumbnail width


$thumbHeight = $height; Thumbnail High


$_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 original size is smaller than the current size


$thumbWidth = Floor ($thumbWidth * $sourceHeight/$thumbHeight);


$thumbHeight = $sourceHeight;


}


if ($sourceWidth < $thumbWidth) {


$thumbHeight = Floor ($thumbHeight * $sourceWidth/$thumbWidth);


$thumbWidth = $sourceWidth;


}





$s 1 = $sourceWidth/$sourceHeight; Original Ratio


$s 2 = $width/$height; New Figure Proportional


if ($s 1 = $s 2) {





} else if ($s 1 > $s 2) {//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)); Analog original ratio 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 how the crop is cut, scale for equal scaling, not cut, not enough place with white fill, crop for cutting, if the requirements of the width and height ratio is larger than the original, then keep the maximum display width, center cut upper and lower redundant parts, if the requirements of the ratio of width to height is less than the original ratio, Then keep the maximum height, center cut around the extra parts, in a word, in the premise of keeping the deformation, the picture to shrink, and the largest retention of the content of the picture. Haha this code has more Diao, try to know,,, of course you need to support rewrite features and GD2 support

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.