PHP images are automatically cropped to cope with display of different sizes, _PHP tutorial

WBOY
Release: 2016-07-13 10:16:56
Original
720 people have browsed it

PHP images are automatically cropped to accommodate displays of different sizes,

If you have ever done that kind of portal site, you must know that a picture may be displayed in different places, with different sizes and proportions,
If you only use one picture, it will definitely be deformed, and it is too wasteful to link the large picture where the small picture is displayed... Using thumbnails to process it is not perfect, because it appears everywhere The proportions may be different, here is an example!

Please see the picture above.

In this place, what is actually transferred is a list, but the size of the pictures is different, some are wide and some are narrow. What should you do when you encounter such a situation? If you use the original address directly, It will definitely be deformed. It is unreliable to use thumbnails. This adjustment is automatically adjusted. You have no idea what width and height a picture needs.
-------------------------------------------------- -------------------------------------------------- ---------------
Let’s get to the point:

I have always used a method, which is PHP automatic cropping...compared to the image address you have seen similar to /aaaa/abc_200_100.jpg or /aaaa/abc_200*100.jpg
My method is to convert the image address into an address similar to the one above where the image is needed, and then direct it to a processing program through apache's rewrite. Generate an image based on the width and height and save it,

There are several advantages to doing this:

First, it is very flexible. Wherever there is a picture, you can control it as wide or as high as you want without deformation, and the program will always display the maximum picture content
Second, when the image is generated once, apache will not redirect to the program next time, because there is a judgment of !d !f in front of the rule, which means that the current file will not be redirected until it does not exist. Next time the picture exists, it will not appear again and will be the real picture

The disadvantage is that there may be more pictures generated and take up more space, but if it is your own server, it doesn’t matter. You can categorize and sort it out

OK, here’s the code, let’s take discuz as an example

Copy code The code is as follows:

function crop_img($img, $width = 200, $height = 200) {
$img_info = parse_url($img);
/* External links directly return 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);
/* External links directly return 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('original image address', 'width', 'height'); This function returns the processed image address. The img function directly returns the image label string. For example, call this function in the discuz template {eval img( $pic,200,100)}
The returned address is /data/attachment/forum/aaaaaa_200_100.jpg. Currently, this image does not exist. Then look at the second step

Step 2: You need to add apache’s rewrite rules
Copy code 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 files that do not exist at the beginning of the address data/attachement/ are directed to image.php for processing, and the url is passed as a parameter

The third part is the code in image.php
Copy 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]; //原图宽
$sourceHeight = $imageValue[1]; //原图高
$thumbWidth = $width; //缩略图宽
$thumbHeight = $height; //缩略图高
$_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) { //如果原图尺寸小于当前尺寸
$thumbWidth = floor($thumbWidth * $sourceHeight / $thumbHeight);
$thumbHeight = $sourceHeight;
}
if ($sourceWidth < $thumbWidth) {
$thumbHeight = floor($thumbHeight * $sourceWidth / $thumbWidth);
$thumbWidth = $sourceWidth;
}

$s1 = $sourceWidth / $sourceHeight; //原图比例
$s2 = $width / $height; //新图比例
if ($s1 == $s2) {

} else if ($s1 > $s2) { //全高度
$y = 0;
$ax = floor($sourceWidth * ($thumbHeight / $sourceHeight));
$x = ($ax - $thumbWidth) / 2;
$w = $thumbWidth / ($thumbHeight / $sourceHeight);

} else { //全宽度
$x = 0;
$ay = floor($sourceHeight * ($thumbWidth / $sourceWidth)); //模拟原图比例高度
$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();
}

thumb 函数 可以控制 裁切方式,scale 为等比缩放,不裁切,不够的地方 用白色填充,crop 为裁切,如果要求的宽高比 大于原图宽高比,那么就保持最大显示宽度,居中裁切上下多余部分,如果要求宽高比小于原图宽高比,那么就保持最大高度,居中裁切左右多余部分,总而言之,在保持不变形的前提下 ,把图片缩小,而且最大保留图片的内容.哈哈 这个代码有多叼,试试知道了,,,当然你需要支持rewrite功能和GD2 支持

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/895117.htmlTechArticlePHP pictures are automatically cropped to cope with display of different sizes. If you have ever done that kind of portal site, you will definitely know. An image may be displayed in different places, with different sizes and proportions, if...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!