Upload, Crop and Resize images in PHP

 There is a lot of PHP classes for upload, resize and crop images. But I created this one for many reasons as mentioned below:

  • Ease of use.
  • Flexibility.
  • PHP version: 5 or later.
  • Can upload, resize and crop image.. All in one.

After knowing the reasons for making this class, let's know how it works.

Let me explain first how to manage an image to be uploaded and then to be cropped or resized.
<?php
$uploader = new uploader();
// Setting properties then Uploading the image
$uploader->source = $_FILES['field_image'];
$uploader->destDir = "images/";
$uploader->upload();
// =====================
// Or you may use this too
$uploader->destDir = "images/";
$uploader->upload($_FILES['field_image']);
?>
Note: upload() returns the file name uploaded.

To get error messages, use this code:
<?php
echo $uploader->getError();
// This function will return all errors occured while uploading the image. But it's not printing it to print it where ever you want.
?>
And to get Information messages use this code:
<?php
echo $uploader->getInfo();
// This function will return all information to let the user print it where ever he wants.
?>

After uploading this image, we may resize it. To do that use the following code:
<?php
$uploader->newWidth = 75; // in Pexels.
$uploader->newHeight = 75;
$uploader->resizeDir = "images/resized/";
$uploader->resize();
?>
You may also use this syntax:
<?php
// $uploader->resize($file,$width,$height);
// $file could has a value of "" (nothing), in this case we use the last uploader file.
// if the $file has a String value (file url) it will resize this new file.
$uploader->resizeDir = "images/resized/";
$uploader->resize('',75,75);
// Or you may upload and resize in the same line:
$uploader->resizeDir = "images/resized/";
$uploader->resize($uploader->upload(),75,75);
?>

Crop this image after uploading it:
<?php
$uploader->cropDir = "images/cropped/";
$uploader->newWidth = 75;
$uploader->newHeight = 75;
$uploader->top = 20; // Default is ZERO.. This used to set the cropping top location from the original image.
$uploader->left = 40; // Default is ZERO.. This used to set the cropping left location from the original image.
$uploader->crop();
// You may also use this:
// $uploader->crop($file,$width,$height,$top,$left);
$uploader->cropDir = "images/cropped/";
$uploader->crop('',75,75,20,40);
?>

I hope this is helpfull.
If you need more information, please send me a message and I will reply within 24 hours.