Crop an Image in PHP

This tutorial is going to be an interesting one. In this tutorial, I am going to show you how to crop an image in PHP.

I always show you the simplest and easy way in my tutorial. So, in this tutorial also there is no exception.

You are going to see the simplest and easy way of cropping an image in PHP.

Many newbies think working with the media file in PHP is hard. But this is not true. PHP has a nice system and there are lots of inbuilt functions available to work with images.

Now let’s see how we can crop an image in PHP.

Code snippets to crop an image in PHP

Suppose, we have an image img.jpg. Now we want to crop this image and name it img-cropped.jpg for the new cropped image file name.

Below is given our code snippet of a few lines that can crop our image easily:

<?php
$img = imagecreatefromjpeg('img.jpg');
$imgcrop = imagecrop($img, ['x' => 0, 'y' => 0, 'width' => 655, 'height' => 455]);
if ($imgcrop !== FALSE) {
    imagepng($imgcrop, 'img-cropped.jpg');
    imagedestroy($imgcrop);
    echo "Image cropped successfully";
}
imagedestroy($img);
?>

In the above code, I have used imagecreatefromjpeg() function and pass the image file into that function.

In our case, we have worked with a JPG-type image file having the .jpg extension. Note that, if the image is a PNG-type image, then we would use imagecreatefrompng() function instead of imagecreatefromjpeg() to create the image.

 

Also, read:

The imagecrop() function is responsible for cropping the image that I have used in the code.

In the imagecrop() PHP function, we have passed the crop point ‘x’, ‘y’ and height, width of the cropped image. The imagecrop() function used to crop an image for a given rectangular area with the height, width and cropping point from where the rectangular area selected we set in the parameter.

After that, we used the PHP imagepng() function to create our image from the cropped image data and save it with the name img-cropped.jpg.

We have taken it inside an if condition and display the message if our image is successfully cropped.

The imagedestroy() function I have used to remove the memory from the server that is associated with the task we done.

 

Now you can see that we have successfully cropped our image in PHP. You can now test the code with your image on your server to see if it is working.

 

Leave a Reply

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