THIS IS AN OLD POST – This code still works but is not optimised for current systems and code libraries

I have been using the foundation of this script for the last few years to upload files – particularly imagery – and then quickly and easily resize or create multiple thumbnails of the file. The version I had been using only handled jpegs but I have now expanded it to handle transparent PNGs and GIFs – as well as opaque – and WBMPs.

So what is special about this script – here is a list of its features:

  • Uploads any image / file
  • Creates destination folder if it does not exist
  • Safely renames the file – removes spaces, special characters etc
  • Options to overwrite, make unique, abort or throw error if duplicate found
  • Easily create multiple resized images
  • Easily crop images to particular height and width from given XY coordinates
  • Keep or ignore aspect ratio
  • Specify new filenames
  • Add a prefix to the filename
  • Pad the resized image to the exact size required – or resize to longest size
  • Change the padding colour or make it transparent
  • Convert the image to a particular type (jpg, gif, png, wbmp)
  • Specify the image quality/compression – jpg and png only
  • Option to upscale smaller images or not
  • Return options: true/false | array of image details | new filename | output image to browser | blob


To UPLOAD a file just use:

To RESIZE the uploaded file


I’m not sure how many of you (like) me have used JavaScript cropping scripts to allow your users to draw a crop box over an image and then want PHP to cut the image to that size – well I have used various jQuery image cropping scripts as well as some Mootools ones and most of them are very good but come with limited PHP image handling scripts – so I built a cropping method into this one. It is all available in the download link below but to use it you can just upload (and/resize) your image then call:

This will then crop your image to the height and width you specify starting from the X/Y positions you pass and return it in the format you request (array containing info, full path of image, boolean on success or blob). The script requires all 4 parameters (W/H/X/Y) in order to work and also requires the $myImage->source_file to be set – although this is automatically set via the upload or resize methods.

One other addition is that you can now also output a “blob” so you can store the raw image data in a database rather than to the filesystem.


To use some of the other features just look through the code at the top of the class – it should be self explanatory.

You can DOWNLOAD THE SCRIPT HERE: PHP image upload and resize class – I have included a test form at the bottom so yo can quickly test it – but I would advise you remove it if you use it in a proper application.

I have also put together a little example demo script for uploading, cropping and resizing an image using jQuery and jCrop, and of course this script – you can view the demo here: and download the source files from:

As always I really appreciate feedback on these scripts – so if you like it and use it PLEASE comment below or retweet this post – you can also tweet me @mjdigital – it is the only way I know if I should keep adding these scripts.


  1. […] This post was mentioned on Twitter by Ann Smarty and Scott DeToffol, Mark Jackson. Mark Jackson said: Just released my PHP image upload and resize script – feedback appreciated: […]

  2. Mat Hawker
    Dec 18, 2009

    Nice Script MJ.

    Just wondering what command we are calling to keep the ratio of width and height the same.

    As at the moment it just puts a blank color in the background to fill this extra space.

    • mj7
      Dec 23, 2009

      Sorry for late reply – to ignore the aspect ratio just add:

      To keep the aspect ratio the same as the source and NOT pad it out with the supplied background colour do not use the above but use:

      If you look at the top of the code you’ll see a load of preset variable looking like:

      etc – you can alter any of these for each call by using this syntax in your main page code:

      Hope that helps

  3. jonmoore2
    Feb 15, 2010


    This is genius! Has to be the best object I've found for image resizing….

    Thanks for sharing it!

  4. Zri
    Mar 16, 2010

    Very very nice code. I love it. Thank you so much for it!
    Only issue I am having when resizing very large images, it uses up the memory allocated to php. Is there a way maybe the script can be improved with a few more imagedestroy() comands somewhere, so it works a bit better with larger images?

    • mj7
      Mar 16, 2010

      Zri – thanks for the comments, much appreciated. I will take a look and see if I can improve efficiency. If I can then you’ll be the first to know.



  5. php answers
    May 21, 2010

    Very nice bit of code there, thanks for sharing

  6. Tomas
    Jul 02, 2010

    Thanks for the image upload class. I have a question ..
    everytime I upload a picture, it duplicates the file ( I have got unique name option as true). so If I upload a file named my_image.jpg to an empty uploads/ folder, it creates my_image.jpg and my_image1.jpg. if I upload the same file again, it creates my_image2.jpg and my_image21.jpg and so on. I have noticed that first file is of original width and height and the copy one is of size as set in script. So in above case my_image.jpg and my_image2.jpg have height and width as of the file uploaded and my_image1.jpg and my_image21.jpg have new dimensions as per setup. Any ideas how I can avoid this?

  7. mj7
    Jul 02, 2010

    Tom – thanks for your comment. Can I just ask if you are resizing as well (as in running the ->resize() function) – if you are then that will probably be the issue. If you upload() first it will create one image – when you then resize the same image you will get a new image create if you are using the “unique” flag.

    What you'll need to do is set duplicates to unique before you call upload() then redefine as 'o' (overwrite) after calling upload() but before calling resize() – that will then resize the originally uploaded image – leaving you with only one image upload.

    let me know if that solves the issue.


  8. Tomas
    Jul 05, 2010

    Thanks Mark, it really helped. Nice work.

  9. Ron
    Oct 31, 2010

    If you need a way to upload and process multiple images then here is an example of how to do that. Mark was very generous with his time and helped me put this together… So hopefully this will help others as well.

    The following in conjuction with Mark Jackson's PHP Upload and Resize image class will do the following.

    1) Places the uploaded files in the uploads directory.
    2) Resizes the original file(s) to 800×600 and places them in the uploads/large/ directory.
    3) Creates thumbnails of 200×100 and places them in the uploads/thumbs/ directory.
    4) Deletes the original files unless you comment out those 3 lines near the end of the script.

    Create the following 2 files and place them on your web server together. I would place them in the web root first for testing before moving them. You may also need to create the uploads directory and make sure it's writable. Enjoy.

    Create a file named post.php then copy & paste this form into it.

    <form action=”postconfirm.php” enctype=”multipart/form-data” id=”f1″ method=”post” name=”f1″>
    <input id=”image” name=”image[]” size=”60″ type=”file”>

    <input id=”image” name=”image[]” size=”60″ type=”file”>

    <input id=”image” name=”image[]” size=”60″ type=”file”>

    <input id=”image” name=”image[]” size=”60″ type=”file”>

    <input name=”submit” type=”submit” value=”Submit”>

    Create a file named postconfirm.php and copy & paste the following script into it.

    if(isset($_FILES['image'])) {

    //echo “


    $myImage = new _image;
    $myImage->uploadTo = 'uploads/';

    if(is_array($_FILES['image'])) {

    $keys = array_keys($_FILES['image']);

    $counter = 0;

    $uploadeImages = $_FILES['image'];

    foreach($uploadeImages as $k => $ar) { // LOOP

    if ($_FILES[“image”][“error”][$counter] == 0) {

    //echo “Original file name = “.$_FILES[“image”][“name”][$counter].”

    $img = array(); // START NEW IMAGE ARRAY

    foreach($keys as $key) { // LOOP

    if($uploadeImages[$key][$counter]!='') {

    $img[$counter][$key] = $uploadeImages[$key][$counter];
    if(!empty($img)) {

    $res = $myImage->upload($img[$counter]);

    if($res) {

    $myImage->namePrefix = '';
    $myImage->newPath = 'uploads/large/';
    $myImage->newWidth = 800;
    $myImage->newHeight = 600;
    $o = $myImage->resize(); // RESIZES ORIGINALLY UPLOADED IMAGE

    //echo “800×600 Image Name = “.$o['image'].”

    $myImage->newWidth = 200;
    $myImage->newHeight = 100;
    $myImage->newImgType = 'jpg'; // FORCE OUTPUT TO IMAGE TYPE

    $myImage->newPath = 'uploads/thumbs/';

    // RESIZE
    $i = $myImage->resize();

    //echo “200×100 Image Name = “.$i['image'].”

    $path = “uploads/”.$res['image'];
    if(!empty($path)) {

  10. Ecksbed
    Feb 28, 2011

    Can this script resize images in memory or does it only resize images already saved after upload? I need a script to resize the image in memory, FTP it to another server, then destroy the original without saving to any local disks.

  11. Programmer
    Mar 01, 2011

    Nice script for upload and resize images…/

  12. W Pothof
    May 23, 2011

    I would like to use this script in just a lighty diverent way:
    to have a second thumb, just smaller then the first one.
    What lies are neccecery to be able to do that, say for a second thumb of max size 150×150.

  13. mj7
    May 23, 2011

    You can create as many thumbnails as you like by just calling $myImage->resize(). You can change the settings before each call to alter how the thumbnails come out – e.g:

    $myImage->newPath = 'uploads/thumbs/';
    $myImage->namePrefix = 'th_1_';
    $myImage->newWidth = 200;
    $myImage->newHeight = 200;
    $th1 = $myImage->resize(); // creates small thumbnail: th_1_imgName.jpg
    // Add another thumbnail
    $myImage->namePrefix = 'th_2_';
    $myImage->newWidth = 150;
    $myImage->newHeight = 150;
    $th2 = $myImage->resize(); // creates small thumbnail: th_1_imgName.jpg

    The above uses namePrefix to prefix the image name with whatever you want (in this case “th_1_” and “th_2_”) – if you do not want the prefixes you can leave it out and just set $myImage->duplicates to “u” to make each new thumbnail name unique.

    Hope that helps

  14. W Pothof
    May 24, 2011

    that did help, tho afther i finished it i decided one thimb was enough :p
    Tho thank for your reply.

  15. yammez
    Jun 29, 2011

    Hey there, I found an error in the script when trying to force PNG output, which is necessary for transparent padding (either that or GIF). Anyhoo, for the newImgType to work it gets set within the resize() function, in this switch:
    switch ($image_info['mime']) {

    There are four cases here, and in each there's a line like this:
    $this->imgType = ($this->newImgType!='') ? $this->newImgType : 'gif';

    It needs to be changed to this:
    $this->imgType = ($this->newImgType!=='') ? $this->newImgType : 'gif';

    Changed the != to !== (where it checks for a blank string), otherwise it will never use your newImgType.

  16. mj7
    Jun 30, 2011

    Yammez – thanks for this – I have updated the file to include the strict checking, hopefully you should find it now works out of the box (so to speak). 

    And as a “thank you” I have added in another method which allows you to crop the image to a certain height/width specifying the x and y point to start from  – this is great if using jQuery or Mootools style cropping scripts. I have updated the description above to include info on the cropping tool.

    Thanks for helping make it better.

  17. Chuck
    Aug 03, 2011

    Hi There,

    I love the script! Thank you very much for posting it.

    I think I found a small bug – If you set $imgQuality to anything greater than 95, it will throw GD error when resizing a PNG.

    The reason:

    This function can only accept an integer from 0-9 for $quality and the current logic (100/10) returns 10.

    imagepng($canvas, $path . $preFix . $imgName, $quality);

    My Fix:

    I added an if statement where the $quality variable is created. Below:…

    if (intval($this->imgQuality) > 90) {
       $quality = 9;
    } else {
       $quality = round(intval($this->imgQuality) / 10);

    Hope this helps.

    Thanks again for the script! Love it!


  18. mj7
    Aug 03, 2011

    Aha – I missed that one, thank you for pointing it out and providing the fix. I have implemented your fix as:

    case 'png':$quality = (intval($this->imgQuality) > 90) ? 9 : round(intval($this->imgQuality)/10);

    I have also started putting a few thanks into the comment at the top of the script for everyone who has helped make this script better. If you would like your credit altered in any way (e.g. a web address etc) then please let me know.

    Thanks again

  19. Mike
    Aug 25, 2011

    Man, this is really amazing, thanks for sharing this script! You're a genius! 🙂

  20. checker
    Aug 27, 2011

    I would like to use this script in a GNU GPL licensed software.
    Is that possible?
    The class file only contains
    Copyright MJDIGITAL ©2009 Written by Mark Jackson – All rights reservedI am not sure if the license will be compatible.


  21. mj7
    Aug 30, 2011

    Checker. To be honest I was not expecting such a positive response to this script so did not bother releasing it on GPL. With that said I think it is something I will have to do pretty soon as it appears a few people are using it.

    So for the moment please feel free to use it as you wish, ideally if you can keep a comment at the top with a reference to me that would always be appreciated.

    I will update the script with the correct license info as soon as I get a spare 5 minutes – plus I think I may need to release it onto Google Code or Github as people are making valid suggestions all the time and they should also be recognised.

    Thanks for your interest – let me know if you have any issues with it or can think of any way you would like it to work better.


  22. checker
    Aug 30, 2011

    Hello MJ,
    that souns good, as this class is working very nice and comes in handy.

    I found a small depracated info regarding ereg_replace:
          #$str = ereg_replace(“[^A-Za-z0-9_-.]”, “”,$str);
    and changed it to work with preg_replace:
            $str = preg_replace(“/[^A-Za-z0-9_-.]/i”, “”,$str);

    One thing I would really love to see is a way to “put” watermarks on the images.
    I don't know if this is an easy task as I am very new to image manipulation.

    This script worked for me without spending lots of hours of try and error.

    Thank you very much.

  23. mj7
    Aug 30, 2011

    Checker – strangely enough I am actually half way through adding a watermark function that will allow you to watermark images using text or other images. It is quite complex as I want to make it as useful as possible so is taking a little time (of which I have little) but it is probably my next update. I'll let you now once it is ready.

    And thanks for the depreciation fix – I'll add that into the next update.

  24. checker
    Aug 30, 2011

    Hello MJ,
    thanks for this.
    I really appreciate this and as I can see from the comments I am not the only one. 🙂

    Kind regards,

  25. MX-SA
    Oct 10, 2011

    Hi MJ7 – Thanks for the script ! When i upload the file name to mysql, i must find a way to only upload the name+ext and not the path+filename, how can I go about this?

  26. Pigwa
    Oct 15, 2011

    I think your script is very good but I have problem with using. 
    I am trying to save everything in one file but does not go… 
    I do not understand PHP with PDO-library and with these classes
    Do you can explain to me step by step how to save and use it?

    BTW. You forgotten fixed:  $str = preg_match(“[^A-Za-z0-9_-.]”, “”,$str);  // line 93

    Sorry for my English.

  27. Mog
    Oct 20, 2011

    hi Mj,

    Thank you for sharing this solution. Unfortunately im not an expert of php, i was wondering do you have a more comprehensive example(s) ? with the jquery (jcrop…etc) blend together ?

    Thank you.


  28. Eoin McGonagle
    Nov 03, 2011

    I am having a little difficulty adding a crop function to the thumbnail code above. What I need to do is reduce the size of the picture to 100px wide, then crop that image (which will vary depending on the individual files) to a size of 100px wide 75px high. I want x and y variables to be set to 1. The strange thing is that I can resize the file, or I can crop the file but not both. When I try to do both I get error: “Fatal error: Call to a member function crop() on a non-object in /public_html/mod/photos_upload_script.php on line 107″My code at that section looks like this:

    $myImage->setPosition = 'cc';
    $myImage->padToFit = 'false'; 
    $myImage->newWidth = 100;
    $myImage->newImgType = 'jpg';// FORCE OUTPUT TO IMAGE TYPE

    $myImage->newPath = '../gallery/thumb_temp/';

    // RESIZE 

    $myImage = $myImage->resize();

    $tb = $myImage->crop(“100″,”75″,”1″,”1”);

    If I change the line that reads”$myImage = $myImage->resize();” to “$i = $myImage->resize();” (as in the above script) allit does is crop the original uploade large raw image before it is resized to 100px wide. How can I load the resized 100px wide image and have it cropped and have the path and file name outputed to a variable. Many Thanks, Eoin.

  29. mj7
    Nov 03, 2011

    Eosin – your problem may be caused by you using the same variable name and source for your resized image as you used for the initial class instance. Try changing to:

    $resized = $ myImage->resize();
    $cropped = $myimage->crop(“100″,”75″,”1″,”1”);

    Any better?

  30. mj7
    Nov 04, 2011


    Sorry for the late reply (been on holiday!). Thanks for pointing out line 93 – Have fixed that now. As for step by step instructions, I can't honestly say I understood exactly what you meant by wanting to save everything in one file – are you trying to perform multiple manipulations on the same image (e.g. upload, resize and crop) – if so please see a comment I replied to above to Eoin – or are you wanting the class to be within the same PHP file as your upload form? If the latter then the script actually has an example form at the bottom which is in the same file.

    If I missed the point of what you are asking please could you clarify a little what you are wanting to achieve?


  31. Eoin McGonagle
    Nov 04, 2011

    Ok, I've changed my code to :
    // SET PROPERTIES FOR CREATING THUMBNAILS $myImage->setPosition = 'cc';$myImage->padToFit = 'false'; $myImage->newWidth = 100;//$myImage->newHeight = 75;$myImage->newImgType = 'jpg'; // FORCE OUTPUT TO IMAGE TYPE // PATH FOR STORING TEMP THUMBNAIL.$myImage->newPath = '../gallery/thumb_temp/';// RESIZE $resized = $myImage->resize();//Crop$myImage->source_file=$resized;$myImage->newPath = '../gallery/thumbs/'; //PATH FOR FINAL THUBNAIL$cropped = $myimage->crop(“100″,”75″,”1″,”1”);

    I'm still getting the error: “Call to a member function crop() on a non-object in…”It doesn't seem to be loading the resized image into the crop function?

  32. mj7
    Nov 04, 2011

    You're using a lowercase 'i' in your last call to myImage – change the line:

    $cropped = $myimage->crop(“100″,”75″,”1″,”1”);
    $cropped = $myImage->crop(“100″,”75″,”1″,”1”);

    One thing I did notice is that if you resize the image to 100×75 keeping the aspect ratio then it will possibly create a thumbnail which is actually smaller than that – for example if you upload an image which is 600px x 300px you will actually get a thumbnail 100px x 50px – which when you crop to 100×75 will give you black space below it.

    To help you out with this I have just added an oversize variable to the script (you will need to re-download the class again). To use it just call the following before your resize:

    $myImage->oversize = 'true';

    This will then create a thumbnail which keeps aspect ratio but at least fills the height and width you set – for example if you upload an image 600×300 and resize to 100×75 the actual image size you get will be 150×75 – then you can crop it to 100×75.

    Does that help at all?

  33. Eoin McGonagle
    Nov 04, 2011

    Little strange at the min. I have used a jpg of 1152w x 864h. When I upload and process it what happens is that the resize function resizes it to 581w x 436h and then takes a 100×75 crop of the top left hand corner. If I comment out the new “oversize” line and the section beginning “//CROP” it will resize as expected to 100px but I am back to square 1 where I can't get the crop function to work on the new temp thumb file. Any ideas?

  34. mj7
    Nov 04, 2011

    Odd – it works fine when I test it using just the following code:

    error_reporting(E_ALL);ini_set('error_reporting', E_ALL);ini_set('display_errors',1);include('_image.php');$myImage = new _image;$myImage->source_file = 'test2.jpg';$myImage->oversize = 'true';$myImage->setPosition = 'cc';$myImage->padToFit = 'false';$myImage->newWidth = 100;$myImage->newHeight = 75;$myImage->newImgType = 'jpg';// PATH FOR STORING TEMP THUMBNAIL.$myImage->newPath = 'testDir/temp/';// RESIZE$resized = $myImage->resize();// SET NEW SOURCE$myImage->source_file=$resized;//PATH FOR FINAL THUBNAIL$myImage->newPath = 'testDir/temp2/';// CROP$cropped = $myImage->crop(“100″,”75″,”1″,”1”);echo '


  35. Eoin McGonagle
    Nov 04, 2011

    We have lift off!! 🙂 In the resize function both the width and height need to be defined for the oversize function to work. As I was only defining the width, assuming this would scale the height down appropriately, it was causing some sort of confusion. Many thanks mj7 for all your hard work and help. It is much appreciated. One final strange issue is the large pictures are now being padded in white rather than transparent. Here is the full block of code:
    // REDUCE THE SIZE OF THE ORIGINAL FILE…$myImage->namePrefix = '';$myImage->newPath = '../gallery/large/';$myImage->padToFit = 'true'; $myImage->newWidth = 670;$myImage->newHeight = 436;$myImage->padTransparent = 'true';$myImage->oversize = 'false';$myImage->newImgType = 'png'; // FORCE OUTPUT TO IMAGE TYPE$o = $myImage->resize(); // RESIZES ORIGINALLY UPLOADED IMAGE// SET PROPERTIES FOR CREATING THUMBNAILS $myImage->setPosition = 'cc';$myImage->padToFit = 'false'; $myImage->newWidth = 100;$myImage->newHeight = 75;$myImage->newImgType = 'jpg'; // FORCE OUTPUT TO IMAGE TYPE oversize” rel=”nofollow”>http://www.thesoulcirclegang.c… = 'true';// PATH FOR STORING TEMP THUMBNAIL.$myImage->newPath = '../gallery/thumb_temp/';// RESIZE $resized = $myImage->resize();//Crop$myImage->source_file=$resized;$myImage->newPath = '../thumbs/'; //PATH FOR FINAL THUBNAIL$cropped = $myImage->crop(“100″,”75″,”1″,”1”);

  36. mj7
    Nov 04, 2011

    Ah yes – I see I have made another mistake in the code and padTransparent is not actually implemented – for now try changing:

    $myImage->padTransparent = 'true';
    $myImage->padColour = 'transparent';

    Let me know if that works – I have removed the padTransparent variable from the new version I am working on but forgot to take it out of the one currently available (new version will support text and image watermarks plus some other minor tweaks).

  37. Eoin McGonagle
    Nov 04, 2011

    Perfect. It works flawlessly. My man you are a gent!  You, and those who have contributed to this script, have created a really fantastic script. Many thanks for all the work and help on this one. If you have a donate button I'd certainly like to buy you a pint.
    For those who want to see the corrected code:
    $myImage->namePrefix = '';
    $myImage->newPath = '../gallery/large/';
    $myImage->padToFit = 'true'; 
    $myImage->newWidth = 670;
    $myImage->newHeight = 436;
    $myImage->padColour = 'transparent';
    $myImage->oversize = 'false';
    $myImage->newImgType = 'png'; // FORCE OUTPUT TO IMAGE TYPE
    $o = $myImage->resize();// RESIZES ORIGINALLY UPLOADED IMAGE
    $myImage->setPosition = 'cc';
    $myImage->padToFit = 'false'; 
    $myImage->newWidth = 100;
    $myImage->newHeight = 75;
    $myImage->newImgType = 'jpg'; // FORCE OUTPUT TO IMAGE TYPE
    $myImage->oversize = 'true';
    $myImage->newPath = '../gallery/thumb_temp/';
    // RESIZE 
    $resized = $myImage->resize();
    $myImage->newPath = '../thumbs/';
    $cropped = $myImage->crop(“100″,”75″,”1″,”1”);

  38. Christian Jackson
    Nov 10, 2011

    Cool script!
    Is there a way to rename the file thats uploaded – rather than using user uploaded filename. i.e. picture_id_xyx ?

  39. mj7
    Nov 10, 2011


    You can use the $myImage->newName = 'picture_id_xyx'; variable if you need – don't worry too much about the file extension it gets stripped out and replaced with the correct one anyway.

    Obviously if you need the new name to match a database record ID you will need to insert the record first and grab the ID before uploading the image but that should be no problem.

    Let me know if that helps or not.

  40. mj7
    Nov 15, 2011


    I have been made aware of issues using the newName setting when uploading files – it worked fine for resize and crop but not on upload. I have fixed this problem now and the new code is in place if you wanted to download again.


  41. mj7
    Nov 15, 2011


        Sorry for the late reply – I have uploaded a fully working example of how to use this script plus the jQuery/jCrop javascript code. You can download the source and try an online version now above.

    Hope that helps. MJ

  42. mj7
    Nov 15, 2011

    You can get the filename by doing the following:

    $image = $myImage->upload / resize / crop // each of these return the full path by default
    $imgName = basename($image); // just get the filename and ignore the path

    Is that what you were after?


  43. mcWeb
    Nov 16, 2011

    Not bad, but why this source not work by default? After uploading image and selecting the cropping area, I press Preview Image – croping not work. Only “Loading” text shows proccess,  but nothing happens. What fix??

  44. mj7
    Nov 16, 2011

    I'm afraid I can't really tell you without knowing a bit more. The crop script example is really just a quick and dirty demo of how you could use the PHP script, I've not really put much effort into the demo, it was really just to showcase the image class.

    I may be able to help you a little further if you could get some error messages out of the script – make sure you set errors to be on – see:… and let me know what you find.

    Sorry I can't be more help


  45. mcWeb
    Nov 16, 2011

    Thanks for reply, Mr., here is copied test –

    Uploading picture proccess is ok, but when pressing Preview Image – nothing happens..Try it Yourself.. 🙁

  46. mcWeb
    Nov 16, 2011

    Nothing was changed in source, I upload immadiatelly to server when unzip. Directories have permissions to upload the files.

  47. mj7
    Nov 16, 2011

    OK I think the issue is due to the demo was written to sit in the root of the domain and so all the includes and links are relative to the root, whereas you have it in a subdirectory. You will need to re-link the file locations to suit your directory structure. I'm sure you should be OK altering the ajax-loader image etc but the main urls you need to change will be in: inc/js/3_crop_extra.js where you need to change the following lines to:

    line 14: jQuery.ajax({url:”/tests/uploads2/inc/cleanup.php”, async:false});
    line 37: url: “/tests/uploads2/inc/previewImage.php”,

    Does that make any difference?


  48. mcWeb
    Nov 16, 2011

    BIG THANKS, now it works!

    But its better to change relative directory configuration e.g


    line 14: jQuery.ajax({url:”/tests/uploads2/inc/cleanup.php”, async:false});

    line 37: url: “/tests/uploads2/inc/previewImage.php”,


    line 14: jQuery.ajax({url:”./inc/cleanup.php”, async:false});

    line 37: url: “./inc/previewImage.php”,

    with adding “./inc/…” not “/tests/uploads2/inc/…”, it makes user easy to manipulate with folders, where to put Your work.

  49. mj7
    Nov 16, 2011

    Yes that would probably be best. One other thing I should mention is that I did not update the image class file within the crop demo source so you may not have the most up-to-date version. Please download the latest image class script using the download link above – I have now introduced version numbers and a change log so should be easier to know if you have the latest file or not.

    Hope it all works for you


  50. mcWeb
    Nov 16, 2011

    Ok, big thanks again, Mr., I`ll allways update version of image class script! Cheers! 🙂

  51. mcWeb
    Nov 19, 2011

    Im report one issue, what is found to make this form fully functional. The scenarious: User uploads image, and select area for crop and press preview. But user dont like selected area after pressing Preview, select again area for crop and press again Preview..Nothing happens, croped area not updated. User doesn`t knows, what happen and what need to next..To select again selected area he needs to refresh page and must upload image again and select again..this must be fixed.

  52. barney
    Nov 23, 2011

    I was very excited then fell at the first hurdle 🙂 ….how do you change the the croping box from vertical to horizontal?….ive used the demo source files and changed your inital values of height/width the other way around for horizontal …however the crop window is always vertical…..what can be be doing wrong?..thanks in advance

  53. mj7
    Nov 23, 2011

    Barney – if you open the file: inc/js/3_crop_extra.js then at the top you will see some more parameters you can change for the crop tool – for info on how to set these see:

    You may also find that in this JS file you may need to change the URL path set on line 37 – and line 14 if you want to use a clean-up script.

    I'm afraid the demo is literally just a quick demo to show off the image class rather than a solution for a frontend cropping tool so it is not particularly robust.

    Anyway let me know how you get on.


  54. barney
    Nov 23, 2011

    ooh quick reply…that quick in fact that you replied before i could comment that i found where to change the ratio 🙂

    My jquery skills are far from the best, so ill need to build on the example..ill let you know how i get on

  55. mj7
    Nov 23, 2011

    No worries – hope you get it working.

    Although me replying so quickly does now look like I have nothing better to do….!

  56. barney
    Nov 23, 2011

    well, as youve got time on your hands….i cant seem to retain the extension of the file….your online example works, my version (based in your files) doesnt…even when i look at the source i have

  57. mj7
    Nov 23, 2011

    Barney – can I just check with you that you are using the most up to date image class? I made some adjustments last week to the extensions and naming issues but had not as yet updated the version compiled in the crop demo. I have now updated the demo version so can you replace the _img.php class in your current version with the latest and let me know if it fixes the problem? Note – if you download the image class on it's own then you will need to remove the test form at the bottom.


  58. barney
    Nov 23, 2011

    ok, i downloaded the files this morning….and now they are different :)…alls working..

    Now onto another thought, im thinking of having a few form fields into the mix, ie. title etc, that then can be added to a db….what are your thoughts on this?

  59. mj7
    Nov 23, 2011

    Sounds like a perfectly normal thing to do. If you are thinking of using my demo script almost as is you may hit a problem in that the only time a post is made is when you first select and upload your image – it is at that point the form is submitted. Then you can create your crop as required and when you hit 'accept' all it does is just go through to the complete.php page and all the imagery is strored in Session variables (again this demo was just a quick proof of concept). If you want to store extra data you may want to resubmit the form a second time when you hit accept or on the complete page you have step two of the process and have another form there..

    Hopefully that makes sense.


  60. joggie
    Nov 24, 2011

    Howzit! Mark,

    I am playing around with the script. Uploaded the class and got stuck. I eventually uploaded the source files found in to a “cropscript” folder in my root folder.

    I am using FireBug in FF to see any errors.
    When going to above the upload field the word Loading appears and Firebug make mention the following: “NetworkError: 404 Not Found –…“
    I am sure its got to do with the paths to be set but am not sure were all the places are where I should set the paths…

    Now… When I select an image and submit, Firebug is giving the following error: setLoader is not defined <— Am also sure its the path in some file that needs to be changed but again not sure where?

    The page then goes blank and gives the following Error message:”Error: The upload failed – the file could not be moved to the target location – please check the permissions”

    It would be much appreciated if you can help.  I am lost in the file structure of your downloadable sample…


  61. mj7
    Nov 24, 2011


    Hmmm – I think I may need to revisit my example and allow easier updating of file paths (to be honest I wasn't expecting the cropscript demo to be the star of this post as it was just a quick and dirty proof of concept for the PHP class).

    To help you out in this instance before I alter any code you can find the loader image linked in index.php as normal and then you need to alter the paths in the PHP section at the top of index.php

    Next you will need to alter the paths in the inc/js/3_crop_extra.js file on line 14 and 37 to match your setup.

    If you want to change the crop dimensions at all this is done also at the top of inc/js/3_crop_extra.js

    Any problems just shout.

  62. joggie
    Nov 24, 2011

    Mark, thanks for the reply.
    I read all the comments on this page and did the changes as indicated in an earlier post.
    line 14 is :     jQuery.ajax({url:”./inc/cleanup.php”, async:false});
    and 37 is:      url: “./inc/previewImage.php”,

    According the earlier convo, this is right. Or am I missing stuff if this is installed in a folder called cropscript in the root.

    I also see that in the cropscript/inc/_img.php file there is another folder mentioned as the upload folder???
    Its on line 35:     public $uploadTo        = './assets/images/uploads/originals/';    // folder to upload to (relative to calling document)

    Thanks for you help…
    How can this script not be a HIT! Of all I have tested… (Image, upload crop google results are burnt to my screen! 😉 ) This script ROCKS… Would be even better if I can get it to work on my system!

  63. checker
    Nov 24, 2011

    Hello MJ,
    thats great news with watermarks.
    Can you say when this version will be released?

    Kind regards,

  64. mj7
    Nov 24, 2011

    I have got as far as building in the text watermark and this allows you to set the text, font, font-size, colour, opacity, shadow offset x & y,shadow colour, shadow alpha and rotation of the text. The next bit is getting it to overlay images at various positions, rotations, opacity, size etc – I think I may have to limit it to just using PNG files for the first release.  I estimate I have about 4-5 hours left on it tops.

    When did you need it by?

  65. mj7
    Nov 24, 2011


    Sorry you've been having issues with the crop demo. Today seems to be a day of them as I've had 4 people contact me or comment with the same issue. So… I have updated the script to make it a bit easier to put in any directory – hopefully you should find this one works out the box. Please download it again and let me have your thoughts. I have also added a few random form fields as that was another request.



  66. Stefan Conradie
    Nov 24, 2011

    Thanks Mark! Will get busy with it, this instant and keep you up to date. 😉

  67. Stefan Conradie
    Nov 24, 2011

    Thanks Mark, Looks as if the folders are sorted but…
    I must add…. After downloading your amended script did I realize it might have been my RewriteRules that stuffed up the script…

    Looks as if all is now sorted and I can start to play with the script….
    Will keep you posted and thanks again for a KING script and all the help! 🙂

  68. mj7
    Nov 24, 2011

    Gasp!! – oh well nevermind – it needed updating anyway.

    Hope it all works for you.


  69. Matiss
    Nov 25, 2011

    New image modalbox upload & crop plugin – mCropper released

  70. Stefan Conradie
    Nov 25, 2011

    Howzit! Mark…
    Was looking at the Multiple upload mentioned in another comment.
    Was thinking… Will it be a bad thing to iframe, say 4 forms on a single page to have this system do multiple uploads?


  71. mj7
    Nov 25, 2011

    Thanks for this – although it would have been a much more powerful tool if you'd used my PHP image class to handle the upload, resize and cropping – you could get it to do an awful lot more (especially when I release the watermark features).

    Also it looks like you are still using the old version of the webmotionuk script which means it only handles JPEGs – I feel a switch is needed – why not give my script a go!!

    But it is down to you.

  72. mj7
    Nov 25, 2011


    Uploading multiple files in a way that is both pretty and usable is always gonna throw issues – do you use iFrames or a Flash uploader or go for HTML5 and JS/Ajax – each solution is not 100% perfect.

    For me I'd probably look at the HTML5 and JS route but that does heavily rely on supporting browsers so maybe the next option would be iFrames. Again it is not without it's issues but is easier to get working from scratch than Flash, is more browser friendly (at the moment) than HTML5 – so yeah, maybe your best bet.

    But, a warning – I would not build too much around iFrames usage – make it so you can easily alter how the system works in the future.

  73. Stefan Conradie
    Nov 25, 2011

    I will be using this in my membership pages where no SEO will be needed.
    I am currently testing the system in 4 iframes on one page to make the multiple image upload.

    So far… It's working nicely.
    With a bit of styling and work on the total look-ups… This system will do the trick.

    For me… This looks as the best option… For now….
    Will keep you posted!

  74. Stefan Conradie
    Nov 28, 2011

    Howzit! Mark.

    Where exactly will we use $myImage->newName = 'picture_id_xyx'; and on what form?
    Sorry if this is a stupid question


  75. mj7
    Nov 28, 2011


    You'd use it either just before you call $myImage->upload() if you want to rename the uploaded image or before $myImage->resize() if you want to rename the resized image. It should be used when processing the form which posts the image. Hope that helps.


  76. Stefan Conradie
    Nov 29, 2011

    Hi Mark…

    I am not sure what I miss but how the script is now, its cropping in portrait….
    How to go about to make it crop in landscape?


  77. Stefan Conradie
    Nov 30, 2011

    I am not sure if I am being stupid, but I tried changing:
    $minWidth            = 200;                                        // set minimum image crop width
    $minHeight            = 150;                                        // set minimum image crop height
    in the demo index.php file, but with no luck.
    This eventually only gives me a portrait crop box and when previewing it display differently from the selected crop section.

    Please help

  78. mj7
    Nov 30, 2011


    I may need a little more info on exactly what you are trying to achieve, however, the following information may help you. The $minWidth and $minHeight parameters set the smallest area the crop tool will allow you to shrink to when dragging the handles. The final image size is set by $img_height_main and $img_width_main.

    The other thing is the aspect ratio of the draggable crop area – this is set by editing the $cropAspectRatio variable. This is a float/integer value and can be worked out by the following equation: width/height. Therefore if you want to have an image which is 200px wide by 150px high you need to set the $cropAspectRatio to: 1.33 ( = 200/150) – the issue here is that the actual aspect ratio is 4:3 which as a decimal is 1.333333 recurring so you may get some issues with it cropping a pixel too short occasionally. To get around this you may need to either revisit your required crop aspect ratio or if you prefer you can add the following to the previewImage.php file:

    Current Line 58: $_image->source_file = $crop;
    ADD THIS: $_image->aspectRatio = 'false';
    Current Line 59: $_image->newWidth = $img_width;

    As the crop tool passes almost the correct aspect ratio anyway then when the image resizes it will resize to exactly the dimensions set by $img_height_main and $img_width_main and fix any issues with the crop aspect ratio – but obviously this may cause the image to stretch by 1 pixel rather than cropping perfectly.

    Hope that is vaguely understandable!


  79. Stefan Conradie
    Nov 30, 2011

    Thanks Mark!
    Something to work with… Am sure this will put me into the right direction.

    Will keep you posted

  80. Jimmy
    Jan 29, 2012

    Great script!

    But I still got a problem with the png transparency. I'm using the updated version with the cropping support. I saw an old comment talking about the same thing, but that was for the older version without the crop feature. I tried different things, but I still got black instead of transparency…

    By the way, there's no big deal, but I have another trouble. Is there a way to don't upload all the resized pictures ? I just need the original, the medium and small thumbnails.

    Please somebody help me!

  81. Ro
    Feb 22, 2012

    Hello I have a problem.
    Why the images are not seen when I push to preview image and instead of turn the image appears the code of the image like that:
    ? T=1329928429761 ” />
    I have tried to put this but it does not work:

    line 14: jQuery.ajax({url:”./inc/cleanup.php”, async:false});
    line 37: url: “./inc/previewImage.php”,

    please if someone can help me, Im love this script. Sorry for my English, Im Spanish.

  82. Daniele
    Mar 02, 2012

    Hello Mark,
    I've found a small bug and fix it.

                // do not upscale image
                if(($s_width<=$this->newWidth)&&($s_height<=$this->newHeight)) {
                    $this->newWidth = $s_width;
                    $this->newHeight = $s_height;


                // do not upscale image
                if(($s_width<=$this->newWidth)&&($s_height<=$this->newHeight)) {
                    $this->newWidth = $s_width;
                    $this->newHeight = $s_height;
                    $c_width = $this->newWidth;
                    $c_height = $this->newHeight;

    If upscale is false also the canvas must have the same width and height size 🙂

  83. NiceOne
    Mar 28, 2012

    Hello,Why I can not turn off the ratio of the two following files?My code looks like this and the ratio for the file 137×108 and 75×75 is on;/
    if (isset ($ _FILES ['image'])) {$ MyImage _image = new;$ MyImage-> imgQuality = '80 ';$ MyImage-> aspectRatio = 'true'; //here must be true – good$ MyImage-> setPosition = 'cc';$ MyImage-> duplicates = 'a';$ MyImage-> newWidth = 650;$ MyImage-> newHeight = 515;/ / $ MyImage-> namePrefix = 'id_czas';$ MyImage-> newname =''. date (“His”).'';$ MyImage-> uploadTo = 'img/800×600 /'. date (“we”). '/';$ res = $ MyImage-> upload ($ _FILES ['image']); $ i = $ MyImage-> resize ();echo '<img src=”'.$i.'”>';echo '
    ';if ($ res) { / / RESIZE / / $ MyImage-> padColour = 'black'; $ MyImage-> aspectRatio = 'false' / / must be false – not found?
    $ MyImage-> imgQuality = '85 '/ / found$ MyImage-> newpath = 'img/137×108 /'. date (“we”).'';$ MyImage-> newWidth = 137; $ MyImage-> newHeight = 108; $ i = $ MyImage-> resize ();echo '<img src=”'.$i.'”>';echo '
    ';$ MyImage-> aspectRatio = 'false' / / not found?$ MyImage-> imgQuality = '90 ';$ MyImage-> newpath = 'img/75×75 /'. date (“we”).'';$ MyImage-> newWidth = 75; $ MyImage-> newHeight = 75;$ i = $ MyImage-> resize ();echo '<img src=”'.$i.'”>';}}Can you help me turn off ratio for 137×108 and 75×75? 🙁

  84. mj7
    Mar 28, 2012

    As far as I can see the aspect ratio has been turned off in your script but it is probably being overridden by the pad to fit function which fills in the extra space with the pad colour to make up the exact image size entered. Can you try turning off the pad to fit to see if that makes a difference – add the line below before you call resize() for the 75×75 and 137×108 image:

    $myImage->padToFit = 'false';

    Make any difference? If not then let me know.

  85. NiceOne
    Mar 28, 2012

    Hello Mark,

    You are right.
    I changed my code by your description and large picture has ratio = true, and smaller picture has ratio = false, and everything very good works!:D

    Now I have another problem…
    I have:

    $newImgType = 'jpg';

    and when I sending .png / .gif then function $newImgType changes to .jpg (good)
    and when I sending .exe / .php / .bat etc.  then receives error “files are not supported” (good)

    BUT..but it saves the file at a specific location in spite of show an error – why?

  86. mj7
    Mar 29, 2012

    Hmmm – you got me there – I will admit I never tried uploading a non-standard image file. Will look into this as well. There are also a few other issues regarding the file type conversion that I am working on so hopefully the next release will fix all this.

    Thanks for the update – I'll get onto it.

  87. Pankit Kapadia
    Apr 17, 2012

    thnx !!

  88. Ed
    Apr 28, 2012

    i'm trying to call the get_image_height function because i want to crop the image in the middle of the canvas, but every time i call the function it says undefined. can you tell me how to do call it properly? thanks!

  89. Npd1164
    May 16, 2012

    In your demo script, when you try to preview a crop selection, IE 8 throws an error message: (console undefined).

  90. Npd1164
    May 19, 2012

    It seems that, in inc/js/3_crop_extra.js, there are three lines which reference console.log(…)  

    From what I've read, console doesn't exist in IE unless the console is actually open.  So… I commented these out and IE8 seems to run this script happily now.  

    I also ran into issues with the testing if this script in Safari – the browser would hang on upload about 50% of the time.  While it turns out that this is a browser bug, I thought i'd post a reference on how I fixed it in case others might run into this issue too:
    (be sure to read the last posted comment – as it includes more info on making it work)

  91. Npd1164
    May 19, 2012

    Oh, I also had to replace the 1_jquery-1.4.min.js   with a minified jquery version 1-7-2  in order to get rid of a “document.documentElement is null…” complaint that i was also getting in IE8.

  92. deejayyz
    Jun 01, 2012

    Hi, i am wondering how to get this working for IE9. Even the demo is not working on IE9. It uploads the file, but when hitting “preview” the loader goes on and on.

  93. Hoshang Sadiq
    Jun 24, 2012

    It's a decent class, however, with the cleanUp() method it is not possible to make sure the filenames are cross platform compatible. As you know Windows' filenames are not case sensitive, whereas in just about every other OS it is. So obviously if you were to move these files from a *nix machine to a Windows machine, or the other around, and files names are the same, it would overwrite each other. I've provided a new cleanUp() method which I think would be better for this.

    bottom is just a test and produces the following results:
    string 'test.png' (length=8)
    string 'asdsd.png' (length=9)
    string 'asd21.png' (length=9)
    string 'dh_f_g9_asd.png' (length=15)

  94. Harry
    Jul 12, 2012

     You my friend, are a genius. Thank you, thank you, thank you.

  95. Hushy
    Jul 17, 2012

    Hello Mark,

    i tried to get it work, but i can upload an image, but i can not crop it. I can see the uploaded image but i can not start the cropping frame.

    Can U help me and ist it possible to send the images to an address by the form?


  96. Hushy
    Jul 17, 2012

    Hello Mark,

    i don't geht the script not working. I can upload an image but while this the circle is already not turning and showing. It just shows me the uploaded image without the cropping tool and that's ist? Can you maybe help me why this happen? the url ist

    And I have an question. Is it possible to send the picture in a form to an email-address? There is already the possibility to ad name etc.

    Thnx in advance.


  97. Clivecorner
    Aug 14, 2012

    Hi there looks like a really good script – unfortunately the script failed when I went to Preview Image – the image didn't appear in the side window. Also  got the following errors in complete.php:

    Notice: Undefined variable: cropperWidth in C:xampphtdocsphscropscriptcomplete.php on line 98

    Notice: Undefined variable: cropperHeight in C:xampphtdocsphscropscriptcomplete.php on line 98Cheers and thanksClive C

  98. mj7
    Aug 15, 2012


    Sorry for the late reply, I have been away. The original code was built to work in the root directory and not in a sub directory (as in orderform/cropscript) – this may seem like a gross error but if was only built originally as a proof of concept rather than a distributable piece of software.

    With that said I have tweaked the code to now allow you to put it in a subdirectory and this should then fix your issues – please redownload the script and try again – then let me know if it works.

    With regards to sending the image to an email you could use another free script called phpmailer and add the image as an attachment or your could write it into the email HTML and link the image to your online version – either way it should be quite simple using phpmailer.

    Any problems just shout

  99. mj7
    Aug 15, 2012


    As the crop tool was only built originally as a proof of concept for my PHP image class rather than a distributable piece of software the original code was built to work in the root directory and not in a sub directory (as in /cropscript folder).With that said I have tweaked the code now to allow you to put it in a subdirectory and this should hopefully fix your issues – please redownload the script and try again – then let me know if it works.


  100. LiveNet
    Aug 18, 2012

    how to limit height, width of uploaded image?

  101. Gatis
    Aug 28, 2012

    Resize to 200×200 and 50×50

  102. Andreas
    Sep 28, 2012

    Hello Mark!

    Just tried in IE9 – The “Preview Image” step does not work

  103. Andreas
    Sep 30, 2012

    Hello Mark! Found a solution a little bit below for IE( thats working for IE9 too

    Just commented out three lines in inc/js/3_crop_extra.js, there are three lines which start with console.log

  104. Andreas
    Sep 30, 2012

    Hi! I am trying to rename the resized images to the name given in the field1, but it did not work. Do you have a solution for that?

  105. Tech Lover
    Oct 17, 2012

    I really like how simple the script is, and it achieves what I want. I currently have a issue. I am not sure if this has to do with the 'web root folder' issue, or if it is something in my code. I am using what I think is the latest version of the script. (
    When I click preview, the script copies/crops the images to the correct folders, But it doesn't show the preview image on the right. Is there any javascript, or php fix I can add to get the preview to work well?
    If there isn't any way to fix it, I can remove the preview image, and change the “preview image” onclick to “process”, and change the accept button to another name.

    Thanks for the script!

  106. tashi
    Nov 05, 2012

    MJ7….nice work… but i am getting following notice wen i click submit button after crop area selection–>undefined variable in previewImage.php on line 57& 77.

    (my doc root –>D:/webs)

    if i close the dialog box and accept i get the following:

    Undefined variable: distance in D:webscropscriptcomplete.php on line 42

    Image upload and crop tool – upload your profile picture and crop it to a set size of
    Notice: Undefined variable: cropperWidth in D:webscropscriptcomplete.php on line 100

    Notice: Undefined variable: cropperHeight in D:webscropscriptcomplete.php on line 100
    x keeping the aspect ratio. Follow the steps in order.

    help please ..thank you in advance MJ7.(

  107. Gatis
    Mar 26, 2013

    This script upload and resize image. Select your image and image will resize to 200×200 px and 50×50 px

  108. kalimba
    Apr 19, 2013

    I could not get this to work until I changed this line:

    // Copy image
    imagecopyresampled($canvas, $src, $x, $y, 0, 0, $s_width, $s_height, $s_width, $s_height);


    // Copy image
    imagecopyresampled($canvas, $src, 0, 0, $x, $y, $s_width, $s_height, $s_width, $s_height);

    I think the src position and destination position need to be swapped to place the newly cropped image on the canvas correctly

  109. surajit
    Aug 03, 2016

    how to get orginal image name after rename image

    • mj7
      Aug 03, 2016

      Surajit – you would need to interrogate the $_FILES superglobal to get that information before the file is renamed.

      The $_FILES variable will be an array of all the uploaded files so if you have only uploaded one file (and it is called “image”) then it should be available by using:


      Hopefully that all makes sense.

      • surajit
        Aug 03, 2016

        my html code

        and php code

        image name show before rename i want to name after rename
        this code no value

        • mj7
          Aug 03, 2016

          Surajit – the $_FILES array is only available before you process the upload and not after so you would need to capture the name before processing, store it somewhere for future use and then recall later if you need it after the file has been uploaded.