Crop A Part Of Image With PHP

Crop A Part Of Image With PHP

While developing an application, there are various reasons to crop a photo. If you know the specific height and width to crop the photo and do not want users to give you an idea from where to crop, you can simply use PHP to crop the photo. This will be the pretty basic option. In this article, I am adding a code to crop a part of the image with PHP.

This PHP code extracts the image part from upper-left corner up to the 100px x 100px. You can change the crop size of the image to whatever you want.

Crop A Part Of Image With PHP

Change the given variable to change the part of the image you want to crop from the image.

<?php

$file= "source.jpg";
list($w, $h, $type, $attr) = getimagesize($file);
$srcim = imagecreatefromjpeg($file);

$srcx = '0';   // begin x
$srcy = '0';   // begin y
$srcw = '100'; // width
$srch = '100'; // height
$dstx = '0';   // destination x
$dsty = '0';   // destination y

$dstim = imagecreatetruecolor($srcw, $srch);
$white = imagecolorallocate($dstim, 255, 255, 255);
imagefill($dstim, 0, 0, $white);

imagecopy($dstim, $srcim, $dstx, $dsty, $srcx, $srcy, $srcw, $srch);

header("Content-type: image/png");
imagepng($dstim);
imagedestroy($dstim);

?>

This code for educational purpose and learn how PHP can be used to crop a part of the photo.

If you need the more advanced solution, you should go with jQuery. With jQuery, you can allow users to select the crop area and then use those dimensions and coordinates in this code o crop the image. To make you work easier, I am suggesting you to go with Image Crop & Uploader jQuery Plugin. This plugin is simple to integrate in any kind of web application. It is paid but costs just $14. So, you can save hours by using this plug and play jQuery plugin to drag and drop photo.

Advertisement

Tags: | | |

Deepanker Verma is the founder of Techlomedia. He is a tech blogger, developer and gadget freak.


Similar Articles

0 Comments

Leave a comment

Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.

2020 UseThisTip | Part of Techlomedia Internet Pvt Ltd Developed By Deepanker