Cropping an image in PHP

Published on: March 28, 2014 Written by: Thokozani Mhlongo

Today we are going to be working with images in PHP. Cropping them basically.

Our ImageCrop class

We are going to be using a class that defines our functions to do the image cropping.

Step 1. Declaring our class and constructor


class ImageCrop {
    protected $_image;
    protected $_preferred_width = 60; //we want 60px of width on image. You can change this
    protected $_preferred_height; //This will be calculated dynamically

    public function __construct( $image ) {
        $this->_image = $image;


Step 2. Define crop() function


public function crop() {
    $dimens = getimagesize($this->_image); //[0] = width | [1] = height
    $ext = $this->get_extension();
    $this->_preferred_height = $this->_preferred_width * ($dimens[1] / $dimens[0]);

    $image_dest = imagecreatetruecolor($this->_preferred_width, $this->_preferred_height);

    $image_as_resource = imagecreatefromstring( file_get_contents( $this->_image ) );

    //Let's do the some image "copying" here
    imagecopyresampled($image_dest, $image_as_resource, 0, 0, 0, 0,
              $this->_preferred_width, $this->_preferred_height, $dimens[0], $dimens[1]);

    //This switch() statement exports the image
    switch ($ext) {
        case 'jpg':
        case 'jpeg':
            imagejpeg($image_dest, "image_small.{$ext}");
        case 'gif':
            imagegif($image_dest, "image_small.{$ext}");
        case 'png':
            imagepng($image_dest, "image_small.{$ext}");

    //Let's do some cleaning up

public function get_extension() {
    return substr($this->_image, strrpos($this->_image, ".") + 1 );
  1. In our crop function we first get the image dimnesions using the getimagesize() function which is a PHP function.
  2. Next we create a black box of our preferred with and height to copy the new image in. This is done with the imagecreatetruecolor() function.
  3. We then create a PHP resource of the image using imagecreatefromstring()to do our resampling with. Cropping will not work if you ommit this step
  4. Now we can copy the image using imagecopyresampled(). What this function does is it copies from one image resource to another using a set of co-ordinates. In our case we are copying the contents original image (from the resource mentioned in bulletin 3) to that black box we first created. We copy from 0,0 (top, left) to the dimensions we received (bottom, right).
  5. Now we enter our switch statement that checks our image extension to determine what type of image to export. There are a number of image exporting functions predefined in PHP such as imagejpeg() , imagepng() , imagegif()by supplying the resampled image resource and the path to save it in. In our case the original and new images are saved in the same directory
  6. Lastly we release some memory by destroying the image resource using imagedestory()

Using it


$image_cropper = new ImageCrop('image.jpg');