Jquery image upload and crop for PHPFriday, November 21st, 2008

Ajax, Articles, Jquery, PHP


We are looking for new features to be added to this plugin, please leave your requests in the comments on the following page : JQuery / PHP Upload and Crop – Feature Request

Finally we had some time to create a full jquery image upload and crop script for php. This latest script is based on the first few versions of PHP & jQuery image upload and crop.

System Requirements

As before you will need the following:

The plan

To upload the image using the one-click upload plugin, crop it using the image area select plugin, save the selected thumbnail and then display the final result. That should be fairly straight forward!

Well thanks to the above plugins it is!


Uploading the file

The jquery one-click upload plugin allows the use of a link or image or button to call the “file browse” window without the need for the “file” input type. Meaning we can make it look “pretty” however we didn’t really bother but you can if you wish. The usage of this plugin is similar to the jquery ajax() function as you can see from the below.

The plugin works by creating and submitting a hidden form with the correct “enctype” something which is not possible using the basic jquery ajax() function.

	var myUpload = $('#upload_link').upload({
		   name: 'image',
		   action: 'image_handling_file.php',
		   enctype: 'multipart/form-data',
		   params: {upload:'Upload'},
		   autoSubmit: true,
		   onSubmit: function() {
		   		//do something when the form is submitted
		   onComplete: function(response) {
		   		//do something with the result

Few things to note:
name: ‘image’ – this is the name of the file that is passed to the script below.
action: ‘image_handling_file.php’ – this is the script that will handle all of out image uploading.
params: {upload:’Upload’} – this is for any additional information that may be required in the script above.
onSubmit: function() – when the “hidden” form is submitted, a function will be executed.
onComplete: function(response) – when the process is complete we recieve the data back from the script which is stored in the variable called “response”.

Once the file has been uploaded, we will pass the file name through the onComplete: function(response), and load this response into an empty div. At the same time we activated the image area select plugin. NOTE: this must be done only after the image has loaded otherwise the cropping functionality will not work.

Cropping the image

This part as usual just grabs the coordinates of the area required and passes it to the image handling script using the jquery ajax function

		type: 'POST',
		url: 'image_handling_file.php',
		data: 'save_thumb=Save Thumbnail&x1='+x1+'&y1='+y1+'&x2='+x2+'&y2='+y2+'&w='+w+'&h='+h,
		cache: false,
		success: function(response){
			//do something with the result

The response from this script will be the final resulting thumbnail. That is really all there is to it…


We are not going to go into the php side of things here as it has been covered in the previous 2 articles. The files in this project are the same as before but have now been split to allow the dynamic capability.

Here is a break down of the files that are now required.

  • index.php – this contains all the javascript functions and is the file used to upload/crop/view the images.
  • image_handling.php – this file processes the upload, resizes the image and deletes images if required.
  • image_functions.php – this file holds the variables and functions to make the whole process possible.

Within the “index.php” and “image_handling.php” files there is an include statement, please ensure this points to exactly where the “image_functions.php” file is on your server!

As with our latest version of the upload and crop script this one also supports upload and cropping for JPG, GIFs and PNGs.

NOTE: Only JPGs that are below 10kb in size are allowed for upload in the demo! The upload folder is cleared every few minutes of all images.

Like it? Share it!

Tagged with:

Feedback (42)

Leave a Comment
  1. eddy says:

    hello please how can i make it support touch

  2. Suresh says:


    It submits the form when i upload a image, Is it possible to upload image without page refresh, i mean using ajax..?

  3. КАРДИК РУ says:

    Some trouble with this script.. I can’t load the JPG picture making with IPhone 5.
    Error – Please select an image for upload.
    Sample picture is here http://yadi.sk/d/N3UrAorBEuM8z

    Plz, help!

  4. It works Amazingly…..Thank you…

  5. Json says:

    How does a 15KB file become 72KB after upload?
    Is there a newer version or a version that contains fixes?

    $max_file = "5";
    $max_width = "300";
    $thumb_width = "730";
    $thumb_height = "170";

    Only need to “upload and resize” an image to 730px by 170px, this script is nice ’cause it allows the user to crop what they want.

    • Chithra says:


      Have you got a solution to save the thumbnail without a fixed thumb width and height?


  6. Json says:

    Blur / smudged image… any way to fix?

    imagejpeg($newImage, $image, 100);

    Trying to set the thumbnail to be 730px by 170px, setting 100 doesn’t help

  7. webb says:

    This is a really cool stuff. Great work guys.

  8. Simon Brückner says:

    I am trying to use the script but have issues with the path where the images are saved:

    I need to use “/Users/myuser/Sites/images/” as $upload_dir so that the chmod stuff works.

    But when the upload has finished, the crop function is broken, as this one expects the path to be “/images/”, not “/Users/myuser/Sites/images/”.

    is there any easy way to adjust the script, or am I just not seeing the solution?

  9. Kevin Wilson says:

    First, thanks for this great tutorial.

    I had everything working, until I started changing the layout of the page. If I put the upload_link anywhere inside a table, it stops working in IE8 – there is no Javascript error, the Open File dialog just doesn’t appear. No such problem in Firefox though.

    Has anybody else had this problem, or does anybody have any suggestions?


  10. Sergio says:

    I forgot to ask:

    a) How to save the thumb with the original name and
    b) How to delete the large image from the server when saved the thumb.



  11. Sergio says:


    In the image_functions.php file, line 126:

    imagejpeg($newImage, $thumb_image_name, 90);


  12. James Womack says:

    Easy to implement and it works. Thank you!

  13. Tal says:

    I love this script! But only one problem that I’d appreciate any help that you can provide:
    I’m trying to set in “index.php” a dynamic condition, and in “image_functions”, based on this dynamic condition (simple “if” statement) I want to dynamically set the “thumb_width” an “thumb_height” variables.

    Although it uploads the file successfully, It gives me errors after I try to crop and save the thumbnail:

    Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in .../image_functions.php on line 109
    Warning: imagecopyresampled(): supplied argument is not a valid Image resource in .../image_functions.php on line 124
    Warning: imagepng(): supplied argument is not a valid Image resource in .../image_functions.php on line 136
    Warning: chmod() [function.chmod]: No such file or directory in .../image_functions.php on line 139
    success, upload_pic/resize_1247993414.png, upload_pic/thumbnail_1247993414.png

    In index.php I put:
    global $test;

    In image_functions I put:
    $thumb_width = “100”; // Width of thumbnail image
    $thumb_height = “100”; // Height of thumbnail image

    Any help?

  14. Ben says:

    Just thought I’d share an issue I had in IE8 with this.

    When preview(img, selection) is first called, the values for selection.width and selection.height are 0.

    This results in it trying to set a css width of “Infinitypx”.

    It only seems to be an issue in IE8, (and it only seems to be a problem for me, which makes me think I’m doing something wrong) but if you’re getting an error in IE8 you might want to check the values of selection.width and selection.height before using them to work out the scale.

  15. Dan says:

    @Mancourt I have the same problem, you can’t use an image either because the div hides it.

  16. Mancourt says:

    Is it possible to make the upload button have a hand cursor to increase usability? I’ve tried all sort of hacks but can’t seem to be able to style that button… It seems like the script generates a div on top of the “upload_link” div… Any ideas?

  17. Jesse says:

    This is amazing. Any way to change the jpeg compression level?

  18. Rob says:

    Great function. I have modified slightly, but want more.

    I would like to have the thumb created automatically. Other functions that create thumbs tend to distort the image. Is there a way to auto create a thumbnail easily from this script?

  19. Nikolai says:

    This is a great solution. Thanks for that!

  20. Joseph says:

    It works fine. Thanks for your great work.

    I have modified the packages to save the thumbnail image to the Server and delete the main image. It works fine.

    But I got an error:

    If I try the photo upload & crop with the SAME image, it doesn’t work on SECOND TIME. It will works fine if I change the image.

    Thank You.

  21. Andy says:

    Hi Guys,

    Really love this script and I’ve got it 99% working. Unfortunately, in IE 7 I’m getting a problem. When I click on the preview image to select the crop area it says there is an error (undefined) and will not let me use the select tool. I’ve implemented the changes mentioned in Todds post, above, to combat the Cache problem. I’ve also moved the thumb_height and thumb_width variables to the upload.php file so they can be dynamic. Works in every browser but IE7.

    Any help would be greatly appreciated!

    Thanks in advance.

  22. Todd Horst says:

    Thanks for the scripts, i modified it a little for a prototype and thought others might be interested.

    I did the jpg mod listed above so that all images are saved as jpg. This makes the images more predictable later on in my code.

    I also changed the image src in both the main image and the preview to look like '+responseMsg+'?'+new Date().getTime()+' this way the images aren’t cached. Before if you uploaded 2 images of the same format (jpg) it would not refresh, adding a timestamp will force it to refresh since it thinks its a new image.

    Lastly, I added $( '#uploaded_image' ).find( '#thumbnail' ).imgAreaSelect({ disable: true, hide: true }); to the onsubmit function of the upload link. This will clear the previous selection and cropper tool and allow another image to replace it. Basically my scenario is that i load the cropper on the page and upload the image and want to display the image in the cropper. Everything is done using ajax so they could possibly change their mind and upload a different image at which time i need to refresh the cropper without reloading the page. This trick should do.

  23. Mahrine says:


    I copied the files in my root folder. When i run the file and click on “Click here to uploa da photo” and select a jpg file of 4 Kb size and click on ok, i get an error msg saying:
    Unexpected Error
    Please try again

    The page cannot be displayedThe page you are looking for cannot be displayed because the page address is incorrect. Please try the following:If you typed the page address in the Address bar, check that it is entered correctly.Open the localhost home page and then look for links to the information you want. HTTP 405 – Resource not allowedInternet Information ServicesTechnical Information (for support personnel)More information:Microsoft Support

    plz help….i have also tried
    but still the same error.
    Any one plz help

    • @Mahrine,

      Ensure all the files are being linked to correctly. We have used include( $_SERVER['DOCUMENT_ROOT']. "/include_file.php" );
      So echo these to the screen (e.g. echo $_SERVER['DOCUMENT_ROOT']. "/include_file.php";) to ensure the path is correct.

  24. Lijith says:

    I want small dot images or something on the corners of the cropping area. How can I add this option to the existing script.

    Thanks for the excellent script provided.

  25. Lijith says:

    Yes I got the result. Just change the line to

    $( '#thumbnail').imgAreaSelect({ aspectRatio: '1:', onSelectChange: preview, x1:0, x2:, y1:0, y2: });

  26. Lijith says:

    I want the the crop area of the tumbnail size to be displayed at the first time it loads. Can I do this option. Please advice.

  27. Chris says:

    Hello, I would like the output to always be a JPG regardless of the file type that is uploaded. Is that possible?

    Thanks! This is great.

    • @Chris, you could try replace the following on lines 80 and 89, then on 121 and 130

      imagegif( $newImage, $image );
      replace with imagejpeg( $newImage, $image, 90);
      imagepng( $newImage, $image ); replace with imagejpeg( $newImage, $image, 90);

      imagegif( $newImage, $thumb_image_name ); replace with imagejpeg( $newImage, $thumb_image_name, 90);
      imagepng( $newImage, $thumb_image_name ); replace with imagejpeg( $newImage, $thumb_image_name, 90);

      Don’t expect great results though. Your best bet is to restrict people to only upload jpgs. Give it a try and let us know how you get on anyways.

  28. Joe Arkley says:


    This script is really great (you should pop a donate button on your page)

    I am hoping to use this script to edit an existing image file on my server. Can you advise me how to remove the form and use an existing file and then upload the new thumb nail and not delete the original.



  29. Chris says:

    I get this error when I upload some of my images?

    Fatal error: Allowed memory size of 16777216 bytes exhausted (tried to allocate 3000 bytes) in /data/16/1/135/37/1461689/user/1571021/htdocs/full_jquery_upload_crop/image_functions.php on line 69

    • @Chris
      Create a “.htaccess” file and put the following line in there:
      php_value memory_limit 24M

      See if that helps. This happens frequently when dealing with images since PHP deals with the uncompressed version of your image (Bitmap). If it’s a large image to start with i.e. 3MB or a high number of pixels i.e. 2000×2000 pixels, this problem may arise, another solution would be to try and upload smaller pictures/dimensions.

  30. Json says:

    Fixed last issue;
    “short open tag” needs to be enabled in PHP.


  31. Json says:

    This script has stopped working on my PC, I hope it’s not MS updates also everything is set, it worked yesterday.

    Now I get this error…
    What should I be looking for?

    Unexpected Error
    Please try again

    ForbiddenYou don’t have permission to access /furkids-org-za/< on this server


  32. cd says:

    hows about animated gif ?

  33. Json says:

    Got it, Added this $(‘#upload_link’).hide();

  34. Json says:

    How to make the text
    “Click here to upload a photo” to disappear after clicking that link?

    Is there a way?
    It’s a bit confusing if you have managed to upload the image.


  35. Json says:

    Common sense kicked in…

    Ok so I am coding my new website and stumbled upon this neat code ‘Jquery image upload and crop for PHP ‘, Wow how cool is this?!!!

    Ok so I need to make it look like my site and add in the norm of javascript, CSS, etc…

    Oh damn the page does not work with my design? WTF???

    Common sense kicks in.
    I load each part individually – including the CSS; Now it works on it’s own with no CSS attached but as soon as I add my CSS it breaks!

    I inspect the CSS and remove parts one by one reloeading the new page each time;

    Found the culprit!!! It’s a form{…} tag in my CSS file.
    I remove this form {…} tag and it works!
    What a freakin’ heacdache!

    Anyways may be a bug but it works in Firefox not in IE7 (the globally lacking ‘browser’)

    Cheers – hope this helps others.
    Thank you again for this neat code!!!

  36. hannes says:

    Hey Guys, great work you’re doin’ here, just wanted to notice it would be awesome if there would be an option to choose between GDlib and ImageMagick since the GDlib has problems running on some 64 Bit Linux Systems (ugly bug that replaces all pixels in a specific colorrange with black ones, can really srew up your day 😉 ) when you try to resize your image – had included that hack in your last version myself, well, whatever.

    Keep on the good work! Hannes

Leave a Comment

You can use these HTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>