Snippets - GD

Snippets index page

Crop an image - Anthony 14/6/2008

Method to crop an image.

  1. <?php
  2. // Crop dimensions.
  3. $width 100;
  4. $height 100;
  5. // Set the path to the image to resize
  6. $input_image "House.jpg";
  7. // Get the size of the original image into an array
  8. $size getimagesize$input_image );
  9. // Prepare canvas
  10. $canvas imagecreatetruecolor$width$height );
  11. // Create a new image in the memory from the file 
  12. $cropped imagecreatefromjpeg$input_image );
  13. // Prepare image  crop - center the crop on the image
  14. $newwidth $size[0] / 2;
  15. $newheight $size[1] / 2;
  16. $cropLeft = ( $newwidth/) - ( $width/);
  17. $cropHeight = ( $newheight/) - ( $height/);
  18. // Generate the cropped image
  19. imagecopyresized$canvas$cropped0,0$cropLeft$cropHeight$size[0], $size[1], $newwidth$newheight );
  20. // Save the cropped image as cropped.jpg
  21. imagejpeg$canvas"cropped.jpg" );
  22. // Clear the memory of the tempory images
  23. imagedestroy$canvas );
  24. imagedestroy$cropped );
  25. ?>

For more examples and information check out the main Imagemagick section.

Change a png to a jpg View

Create some text as an image View

Crop an image View

Display image without saving View

Grayscale image View

Resize an image View

Rotate an image View

Watermark an image View