


PHP images are automatically cropped to cope with display of different sizes, _PHP tutorial
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
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
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
$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 支持

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

Alipay PHP...
