How To Crop Images In PHP – Simple Examples

Welcome to a quick tutorial on how to crop images in PHP. Need to “clip” or “cut” a portion of an image on the server-side? Yes, we can.

We can easily crop images in PHP using the GD extension:

  1. Create an image object $img = imagecreatefromjpeg("SOURCE.JPG");
  2. Define the crop area $area = ["x"=>0, "y"=>0, "width"=>500, "height"=>300];
  3. Crop the image $crop = imagecrop($img, $area);
  4. Lastly, save the cropped image imagejpeg($crop, "CROP.JPG", 50);

That covers the quick basics, but read on for more examples!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Crop Images Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

  • Please make sure that the GD extension is enabled in php.ini.

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

PHP CROP IMAGES

All right, let us now get into the examples of cropping images in PHP.

 

1) SIMPLE IMAGE CROP

1-simple-crop.php
<?php
// (A) CREATE IMAGE OBJECT
$img = imagecreatefromjpeg("cate.jpg");

// (B) CROP AREA
$area = [
  // STARTING POSITON - 0,0 IS TOP LEFT CORNER
  "x" => 0, "y" => 0,
  // NUMBER OF PIXELS TO CROP
  "width" => 500, "height" => 300
];

// (C) CROP IMAGE
$crop = imagecrop($img, $area);
 
// (D) SAVE CROPPED IMAGE
imagejpeg($crop, "demo-A.jpg", 50);

// (E) RECOMMENDED CLEANUP - DESTROY IMAGE OBJECTS
imagedestroy($img);
imagedestroy($crop);

Yep, this is sort of the “full version” of the snippet in the above introduction. Should be very straightforward, but let us expand a little bit more:

  1. Here, we are using imagecreatefromjpeg() to read a JPEG image. If you are working with other formats, use the respective imagecreatefrompng() imagecreatefromgif() imagecreatefromweb(). Yep, this is something I don’t like too, but that is just how GD works.
  2. The crop area is probably the “most painful part” of the crop process. If you want a fixed area, then it’s easy. But otherwise, crazy calculations will be required. Will go through an example below.
  3. Crop the image.
  4. Save the image to a JPG file using imagejpeg(). Same old story, use imagepng() imagewebp() imagegif() if you want other formats instead.
  5. At the end of the script, PHP will automatically clean up the image objects regardless. So this is optional, good to free up some memory if you have more processes to do after saving the image.

 

 

2) CROP FROM CENTER

2-center-crop.php
<?php
// (A) CREATE IMAGE OBJECT
$img = imagecreatefromjpeg("cate.jpg");
 
// (B) CROP AREA
$tocrop = 0.5; // CROP 50% FROM CENTER
$swidth = imagesx($img); // SOURCE WIDTH
$sheight = imagesy($img); // SOURCE HEIGHT
$cwidth = ceil($swidth * $tocrop); // CROPPED WIDTH
$cheight = ceil($sheight * $tocrop); // CROPPED HEIGHT
$sx = ceil(($swidth / 2) - ($cwidth / 2)); // SOURCE X COORD
$sy = ceil(($sheight / 2) - ($cheight / 2)); // SOURCE Y COORD
$area = ["x" => $sx, "y" => $sy, "width" => $cwidth, "height" => $cheight];
 
// (C) CROP IMAGE
$crop = imagecrop($img, $area);
 
// (D) SAVE CROPPED IMAGE
imagejpeg($crop, "demo-B.jpg", 50);

// (E) RECOMMENDED CLEANUP - DESTROY IMAGE OBJECTS
imagedestroy($img);
imagedestroy($crop);

Did I mention that calculating the crop area can get pretty crazy? Let’s walk through it step-by-step.

  • Use imagesx() and imagesy() to get the width and height of the original image.
  • Calculate or specify the area you want to crop out. In this example, it is 50% of the original image.
  • Getting the X and Y coordinates are kind of tricky.
    • First, divide the width by 2 to get the horizontal center of the image.
    • Then, offset it by subtracting half of the desired crop width.
    • Do the same calculation with the height.

 

 

3) CROP & RESIZE

3-resize-crop.php
<?php
// (A) CREATE IMAGE OBJECT
$img = imagecreatefromjpeg("cate.jpg");
 
// (B) CROP AREA
$tocrop = 0.5; // CROP 50% FROM CENTER
$swidth = imagesx($img); // SOURCE WIDTH
$sheight = imagesy($img); // SOURCE HEIGHT
$cwidth = ceil($swidth * $tocrop); // CROPPED WIDTH
$cheight = ceil($sheight * $tocrop); // CROPPED HEIGHT
$sx = ceil(($swidth / 2) - ($cwidth / 2)); // SOURCE X COORD
$sy = ceil(($sheight / 2) - ($cheight / 2)); // SOURCE Y COORD
$area = ["x" => $sx, "y" => $sy, "width" => $cwidth, "height" => $cheight];
 
// (C) CROP IMAGE
$crop = imagecrop($img, $area);
 
// (D) RESIZE & SAVE CROPPED IMAGE
$tosize = 0.8; // SHRINK CROPPED IMAGE TO 80%
$rwidth = ceil($cwidth * $tosize);
$rheight = ceil($cheight * $tosize);
$resized = imagecreatetruecolor($rwidth, $rheight);
imagecopyresampled($resized, $crop, 0, 0, 0, 0, $rwidth, $rheight, $cwidth, $cheight);
imagejpeg($resized, "demo-c.jpg");

Need to further resize the image after cropping? No sweat, just add a few more lines of code. If you want to resize transparent images (PNG GIF WEBP), follow up with my other tutorial on resizing images – Link below.

 

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Crop Image In PHP (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *