Example, cropping images in PHP mainly uses the imagecopyresampled method of the gd library.
Example of cropping an image:
The final cropped picture:
The dotted box is the picture to be cropped, and it will eventually be saved as a 100-wide picture.
Code:
-
-
$src_path = '1.jpg';
- //Create an instance of the source image
- $src = imagecreatefromstring(file_get_contents($src_path));
- //Crop the upper left corner of the area The coordinates of the point
- $x = 100;
- $y = 12;
- //The width and height of the cropping area
- $width = 200;
- $height = 200;
- //The width and height of the final saved image, and the source It must be proportional, otherwise it will be deformed
- $final_width = 100;
- $final_height = round($final_width * $height / $width);
- //Copy the cropped area to the new picture, and proceed according to the width and height of the source and target Zoom or pull up
- $new_image = imagecreatetruecolor($final_width, $final_height);
- imagecopyresampled($new_image, $src, 0, 0, $x, $y, $final_width, $final_height, $width, $height);
- //Output image
- header('Content-Type: image/jpeg');
- imagejpeg($new_image);
- imagedestroy($src);
- imagedestroy($new_image);
Copy code
In fact, if the coordinates is (0,0), and the width and height of the cropped area are consistent with the width and height of the source image, then it is the function of generating thumbnails.
Summarize
Only examples of cropping images in PHP are listed here, which are server-side functions.
If the client needs it, I recommend a jquery plug-in imageAreaSelect, which has very good compatibility.
|