Step One: Install the thinkphp framework
If you want to use the thinkphp framework in your own development, you naturally need to install it into your own project. The installation of thinkphp is very simple. You only need to move the decompressed compressed package directly into the project root directory. After moving, you only need to modify the entry file index.php in the project to start using thinkphp.
Step 2: Introduce the image processing class in thinkphp
Introduce the image processing class in the thinkphp framework to operate images, mainly including basic processing methods such as scaling, cropping, and rotation . Among them, rotation cropping is the focus of this article.
Add the following code in the controller to introduce the image processing class:
use think\Image;
Step 3: Implementation of image rotation and cropping
Rotation cropping is to rotate the image The combined operation with cropping is also very simple to implement. The following is the most difficult part of this article - the code implementation of the rotateCrop function.
/** * 旋转并裁剪图片操作 * @param string $image 被操作图片路径 * @param int $width 裁剪宽度 * @param int $height 裁剪高度 * @param int $degree 旋转角度 * @return bool|string 处理后保存的文件路径或者false **/ public function rotateCrop($image, $width, $height, $degree) { $image = Image::open($image); $image->rotate($degree)->crop($width, $height)->save($image); return $image->save() ? $image->getPathName() : false; }
In this function, we need to pass 4 parameters: image path, cropping width, cropping height and rotation angle. The image path is a required parameter, and the other 3 parameters are optional parameters. The width and The height defaults to zero, that is, no cropping is performed. The rotation angle also defaults to 0, which means no rotation is performed.
The most important of them is the rotation and cropping operations. The Image::open($image) function opens an image object and calls the rotate() and crop() methods in the object to perform rotation and cropping operations. Finally, the save() method saves and outputs the image.
Step 4: Test the effect
Finally let’s test our code. Add the following code to our controller:
$image = 'image/test.jpg'; $width = 200; $height = 300; $degree = 90; $test = $this->rotateCrop($image, $width, $height, $degree); echo '<img src="'.$test.'" />';
In the above code, $image is the target image path, $width and $height are the test cropping parameters, $degree is the test rotation parameter, after execution After our rotateCrop() function returns a saved image path, and finally displays it on the page. After confirming that everything is correct, reload the page and you can browse our processed pictures
The above is the detailed content of How to implement the image rotation and cropping function in the thinkphp framework. For more information, please follow other related articles on the PHP Chinese website!