How to crop image in php using GD Library

In this tutorials we are going to learn about how to crop image dynamically in php using one of php GD library. By this library we can upload and create images in different sizes. It is very helpful if we need a same image in different sizes for our application.

Also it is useful while making any modification on images(png, jpg, gif)


So lets have a look.
First install GD library

crop.php

<?php
# Note: Install GD libraries 
$filename = 'image.jpg'; //orignal file 
$newFilename = 'newImage.png'; // New file after modification 
 
list($current_width, $current_height) = getimagesize($filename);
$left = 0; //crop left margin
$top = 0;//crop right margin
$cropWidth = 1056; 
$cropHeight = 400;
$canvas = imagecreatetruecolor($cropWidth, $cropHeight);
$currentImage = imagecreatefromjpeg($filename);
imagecopy($canvas, $currentImage, 0, 0, $left, $top, $currentWidth, $currentHeight);
imagejpeg($canvas, $newFilename, 100);
?>

Learn more about php GD Library http://php.net/manual/en/book.image.php

If you like this post please don’t forget to subscribe My Public Notebook for more useful stuff.