Crop image in PHP.

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

You can download the uploader.class.php file from this link:
http://www.freelancer-id.com/uploader.class-1.2
This class can:
– Upload images and files.
– Resize images.
– Crop images.

I was looking for a simple way to crop part of an image using PHP code. The idea of this is to create image thumbnail for large images uploaded. These large images could be used for previews, screen shots, wallpapers.. etc.

And because we don’t have an exact ratio between Image width and height, we should crop part of the original image to use it as a thumbnail.

Note: we can find the ratio between width and height and then resize the image. But this won’t work prefect, so we better use cropping to get the size we need.
Also, we can crop part of resized image to use it as a thumbnail.

Let me now explain the code used to crop part of image.


// Receiving image.
$image = $_FILES["image"]["tmp_name"];
// Creating temp image as a source image (original image).
$src = imagecreatefromjpeg($image);

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

// Create new image with a new width and height.
$dest = imagecreatetruecolor($width, $height);

// Copy new image to memory after cropping.
imagecopy($dest, $src, 0, 0, $left, $top, $width, $height);

$path="images/croppedImage.jpg";
$compress = 60;

// Creating new image cropped image as JPG and save it to $dest
imagejpeg($dest,$path,$compress);

// Freeing up memory.
imagedestroy($dest);
imagedestroy($src);

Hope this will be helpful.

Also, you can download the the latest class from: http://www.freelancer-id.com/upload-crop-resize-in-php

Published

By Alaa Badran

Front-End and Web developer

8 comments

Leave a Reply to Somnath Cancel reply

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