Code Example of Picture Proportional Cutting in ThinkPHP
- 2021-11-29 06:27:44
- OfStack
In the development, it is often encountered that pictures need to be scaled according to a certain ratio of 1. However, if a picture with an aspect ratio of 2: 1 needs to be displayed according to a ratio of 1: 1, it means that the picture will be deformed. Here's how to cut and scale pictures in downloading tp framework.
/**
* Cut a picture
* @param $path The path of the picture to be cut
* @param $prefix Prefix the cut picture
* @param $width Proportion of width
* @param $height Proportion of height
* @return string Picture name
*/
function sizeThumb($path,$prefix,$width,$height){
import("ORG.Util.Image.ThinkImage");
$image=new ThinkImage();
$image->open('.'.$path);// Open thumbnails for editing
$imageWidth=$image->width();// Get picture size
$imageHeight=$image->height();
$save_name=getThumb($path, $prefix);
if (($imageHeight/$height*$width)>$imageWidth) {// Cut according to height, if the width is not that long, cut according to width
$image->thumb($imageWidth, ($imageWidth/$width*$height),THINKIMAGE_THUMB_CENTER)->save('.'.$save_name);
}else{
$image->thumb(($imageHeight/$height*$width), $imageHeight,THINKIMAGE_THUMB_CENTER)->save('.'.$save_name);
}
return $save_name;
}
Here, we use the method of taking the largest scale picture from the middle. If you need to use other methods, such as intercepting from the left, modify it.
THINKIMAGE_THUMB_CENTER
'Yes, it is not necessary for the server to take such a way. After all, the front end can also handle it, which should be considered according to the actual situation.
Of course, all images are stored in the relative position of images. If thumbnails are generated, we don't need to use another field to save our thumbnails. We just need to rewrite the cutting and splicing string.
/**
* Get the picture path
* @param $prefix Prefix of picture
* @param $img_url Path of the original image
* @return string Picture path
*/
function getThumb($img_url,$prefix){
$str_arr=explode('/', $img_url);
$last=count($str_arr);
$str_arr[$last-1]=$prefix.$str_arr[$last-1];
$str=implode('/', $str_arr);
return $str;
}
Summarize