Home >Backend Development >PHP Tutorial >PHP gd library implements server-side image cropping and thumbnails

PHP gd library implements server-side image cropping and thumbnails

WBOY
WBOYOriginal
2016-07-25 09:13:14951browse

Example, cropping images in PHP mainly uses the imagecopyresampled method of the gd library. Example of cropping an image: PHP gd library implements server-side image cropping and thumbnails

The final cropped picture: PHP gd library implements server-side image cropping and thumbnails2

The dotted box is the picture to be cropped, and it will eventually be saved as a 100-wide picture. Code:

  1. $src_path = '1.jpg';
  2. //Create an instance of the source image
  3. $src = imagecreatefromstring(file_get_contents($src_path));
  4. //Crop the upper left corner of the area The coordinates of the point
  5. $x = 100;
  6. $y = 12;
  7. //The width and height of the cropping area
  8. $width = 200;
  9. $height = 200;
  10. //The width and height of the final saved image, and the source It must be proportional, otherwise it will be deformed
  11. $final_width = 100;
  12. $final_height = round($final_width * $height / $width);
  13. //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
  14. $new_image = imagecreatetruecolor($final_width, $final_height);
  15. imagecopyresampled($new_image, $src, 0, 0, $x, $y, $final_width, $final_height, $width, $height);
  16. //Output image
  17. header('Content-Type: image/jpeg');
  18. imagejpeg($new_image);
  19. imagedestroy($src);
  20. 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.



Statement:
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