PHP Image Cropping and Resizing


If you have an image and want to create a new image, with new dimensions, you can use imagecopyresampled function:

first create a new image with desired dimensions:

// new image
$dst_img = imagecreatetruecolor($width, $height);

and store the original image into a variable. To do so, you may use one of the createimagefrom* functions where * stands for:

  • jpeg
  • gif
  • png
  • string

For example:

//original image

Now, copy all (or part of) original image (src_img) into the new image (dst_img) by imagecopyresampled:

imagecopyresampled($dst_img, $src_img, 
    $dst_x ,$dst_y, $src_x, $src_y, 
    $dst_width, $dst_height, $src_width, $src_height);

To set src_* and dst_* dimensions, use the below image:

enter image description here

Now, if you want to copy entire of source (initial) image, into entire of destination area (no cropping):

$src_x = $src_y = $dst_x = $dst_y = 0;
$dst_width = $width;// width of new image
$dst_height = $height; //height of new image
$src_width = imagesx($src_img); //width of initial image
$src_height = imagesy($src_img); //height of initial image