PHP pictures automatically cut to cope with different sizes of display _php tutorials

Source: Internet
Author: User
Tags imagejpeg readfile

PHP pictures automatically cut to cope with different sizes of display


If you've ever been a friend of that kind of portal, you know that a picture might show up in different places, different sizes, different proportions,

If you only use a picture, then it will certainly be deformed, and in the display of the small map, link large map, and too wasteful ... It's not perfect to use thumbnails, because the size of each place may be different, for instance!


Please look.

In this place, actually transferred out is a list, but the size of the picture is not the same, how wide the width of the narrow, when encountered such a situation when you do, if directly with the original address, will certainly be deformed, if the thumbnail is not reliable, this transfer is automatically transferred, You have no idea how wide the picture needs to be,
--------------------------------------------------------------------------------------------------------------- ---
Below to get to the chase:

I always use a method, that is, PHP automatic cutting ... Compared to the kind of pictures you've seen,/aaaa/abc_200_100.jpg or/aaaa/abc_200*100.jpg.
My way is to translate this image address into the same address as above, and then direct it to a handler via Apache rewrite. Generate a picture based on the width and then save it,

The benefits of doing this are several places:

First, very flexible, in the picture where you need to how wide and high, you can control freely, will not deform, and the program will always let the picture content display the most
Second, when the picture was generated once, Apache will not redirect to the program the next time, because in the rule before the!d!f this judgment, meaning that the current file does not exist when the direction will go, the next picture exists, will not come out directly is really the picture

Bad place, is the generated pictures may be more, occupy more space, but if it is their own server that doesn't matter, can be categorized under

OK on the code, let's 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 returns 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 returns 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 ';
return;
}
}


function usage crop_img (' original address ', ' width ', ' height '); This function returns the processed image address, and the IMG function returns the image tag string directly, such as calling the function {eval img ($pic, 200,100) in the Discuz template).
So the return address is/data/attachment/forum/aaaaaa_200_100.jpg for now, this picture is not there so look at the second step

The second step is to add the Apache rewrite rule

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 data/attachement/this address does not exist at the beginning of the file is directed to image.php to handle, and the URL as parameters passed

And the third part is image.php in the code.

The code is as follows:



$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]; Original width
$sourceHeight = $imageValue [1]; Original height
$thumbWidth = $width; Thumbnail width
$thumbHeight = $height; High thumbnail image
$_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 chart Scale
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)); Simulated original proportions 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['])) {
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 cutting way, scale for equal than scaling, not cut, not enough place with white fill, crop for cutting, if the requirements of the aspect ratio is greater than the original width and height ratio, then maintain the maximum display width, center cutting up and down redundant parts, if the requirement aspect ratio is less than the original width and height ratio, Then maintain the maximum height, the center cut the left and right parts, in short, in the premise of maintaining non-deformation, the picture is reduced, and the maximum retention of the contents of the picture. Haha this code has more than the mouth, try to know,,, of course you need to support rewrite features and GD2 support

http://www.bkjia.com/PHPjc/896772.html www.bkjia.com true http://www.bkjia.com/PHPjc/896772.html techarticle PHP pictures automatically cut to cope with the different size of the display if you have done that kind of portal friend, must know, a picture may appear in different places, the size is different, the proportion also is different, if only ...

  • 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.