Great Way to Upload, Resize and Crop an Image with PHP

Photo of Mike Dalisay
Modified Wednesday, August 24, 2011
by - @ninjazhai
Hi guys! Today I want to share with you a great way (well, at least for me) to upload, resize and crop an Image with PHP. We're gonna use a class here. I found this class really amazing and works well. This class is really easy and simple to implement.

Great Way to Upload, Resize and Crop an Image with PHP
Great Way to Upload, Resize and Crop an Image with PHP

This is how I used it:

        <title>Upload, Resize and Crop an Image with PHP -</title>
if( isset($_FILES['image'] ) ) { //if the image was uploaded
    //include our class
    include 'libs/img_upload_resize_crop.php';
    //instantiate our class
    $your_image = new _image;
    //To Upload
    //set the location
    $your_image->uploadTo = 'uploads/';
    $upload = $your_image->upload($_FILES['image']);
    echo "<div>" . $upload . "</div>";
    //To Resize
    $your_image->newPath = 'thumbs/';
    //set new image dimensions
    $your_image->newWidth = 400;
    $your_image->newHeight = 300;
    $resized = $your_image->resize();
    echo "<div>" . $resized . "</div>";
    //To Crop
    //dimensions of cropped image
    $width = "150"; 
    $height = "100";
    //we will supply coordinates so that the class would
    //know what part of the image we want to start cropping
    $fromX = "0"; //x coordinate
    $fromY = "0"; //y coordinate
    $your_image->newPath = 'cropped/';
    $cropped = $your_image->crop($width,$height,$fromX,$fromY);
    echo "<div>" . $cropped . "</div>";
    echo "Image was successfully uploaded.";
<!-- Create your form -->
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
    <div><input type="file" name="image" id="image" /></div>
    <div><input type="submit" name="button" id="button" value="Submit" /></div>
If you want more configuration of this class for example you want to decrease the image quality, etc., you can check the class' code which is found in libs/img_upload_resize_crop.php and set your values there.

I run the script and after browsing the image and hitting the submit button, it look like this:

So I got what I want to do with my image after uploading it. Easy and simple right? Thanks to MJDigital.
For FREE programming tutorials, click the red button below and subscribe! :)
Thanks for the comments!
"First do it, then do it right, then do it better."
~ Addy Osmani
"Talk is cheap. Show me the code."
~ Linus Torvalds
Let's Stay Connected!
g+ r
Android app on Google Play
© 2011-2014 The Code Of A Ninja. All rights reserved. Proudly Powered by Google Blogger. Images, logos, marks or names mentioned herein are the property of their respective owners.