PHP & jQuery image upload and crop

Update

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

NOTE: This script has been updated please see the following link PHP & jQuery image upload and crop v1.2 AND the new fully jquery’d version of it Jquery image upload and crop for PHP. Both new scripts handle JPG, GIF and PNG upload and crop!

We needed a PHP and jQuery image upload and crop tool and came up with the following. Hope it helps!

Before you start, ensure you have the following:

  • PHP 4 or Higher (It has been tested on Version 5)
  • Safe mode must be off! – A number of users have reported issues when safe mode is on.
  • PHP GD Library
  • jQuery ver 1.2.3 or Higher
  • Image Area Select plugin by Michal Wojciechowski

Our Requirement

What we needed was a way to upload a JPG image, resize it if required then crop it to given height and width.

1. Firstly we created a form to allow us to upload an image. Pretty basic, nothing flashy there.

Photo

2. Capture, rename and resize the uploaded file. (We also provided a set name for the uploaded file.)

if (isset($_POST["upload"])) {
	//Get the file information
	$userfile_name = $_FILES["image"]["name"];
	$userfile_tmp = $_FILES["image"]["tmp_name"];
	$userfile_size = $_FILES["image"]["size"];
	$filename = basename($_FILES["image"]["name"]);
	$file_ext = substr($filename, strrpos($filename, ".") + 1);

	//Only process if the file is a JPG and below the allowed limit
	if((!empty($_FILES["image"])) && ($_FILES["image"]["error"] == 0)) {
		if (($file_ext!="jpg") && ($userfile_size > $max_file)) {
			$error= "ONLY jpeg images under 1MB are accepted for upload";
		}
	}else{
		$error= "Select a jpeg image for upload";
	}
	//Everything is ok, so we can upload the image.
	if (strlen($error)==0){

		if (isset($_FILES["image"]["name"])){

			move_uploaded_file($userfile_tmp, $large_image_location);
			chmod ($large_image_location, 0777);

			$width = getWidth($large_image_location);
			$height = getHeight($large_image_location);
			//Scale the image if it is greater than the width set above
			if ($width > $max_width){
				$scale = $max_width/$width;
				$uploaded = resizeImage($large_image_location,$width,$height,$scale);
			}else{
				$scale = 1;
				$uploaded = resizeImage($large_image_location,$width,$height,$scale);
			}
			//Delete the thumbnail file so the user can create a new one
			if (file_exists($thumb_image_location)) {
				unlink($thumb_image_location);
			}
		}
		//Refresh the page to show the new uploaded image
		header("location:".$_SERVER["PHP_SELF"]);
		exit();
	}
}

3. Now that the image has been uploaded and saved to our folder we can use the “Image Area Select” plugin to crop our image.

It basically provides the coordinates to the server to handle the crop.

  • x1, y1 = coordinates of the top left corner of the initial selection area
  • x2, y2 = coordinates of the bottom right corner of the initial selection area
  • width = crop selection width
  • height = crop selection height

There are a number of options with this plugin which you can see using the link above. We opted for an aspect ratio of 1:1 (height and width of 100px) along with a preview of what we are actually going to crop.

Lets break it down, we first set the imgAreaSelect function to the image we want to crop, i.e. the one we just uploaded. As you can see, the aspect ration is set to 1:1, which means we are going to get a square selection. The “onSelectChange” is a callback function which runs the preview function when a change is made to the crop.

$(window).load(function () {
	$("#thumbnail").imgAreaSelect({ aspectRatio: "1:1", onSelectChange: preview });
});

The preview function below, is run as soon as you create your selection. This places the right part of the image into the preview window. The second part of the function populates hidden fields which are later passed to the server.

function preview(img, selection) {
	var scaleX = 100 / selection.width;
	var scaleY = 100 / selection.height; 

	$("#thumbnail + div > img").css({
		width: Math.round(scaleX * 200) + "px",
		height: Math.round(scaleY * 300) + "px",
		marginLeft: "-" + Math.round(scaleX * selection.x1) + "px",
		marginTop: "-" + Math.round(scaleY * selection.y1) + "px"
	});
	$("#x1").val(selection.x1);
	$("#y1").val(selection.y1);
	$("#x2").val(selection.x2);
	$("#y2").val(selection.y2);
	$("#w").val(selection.width);
	$("#h").val(selection.height);
}

This function is not really required, but helps by checking to see if the user has made a crop selection. In our case it is a required step. The form is submitted if the values exist, i.e. a selection has been made.

$(document).ready(function () {
	$("#save_thumb").click(function() {
		var x1 = $("#x1").val();
		var y1 = $("#y1").val();
		var x2 = $("#x2").val();
		var y2 = $("#y2").val();
		var w = $("#w").val();
		var h = $("#h").val();
		if(x1=="" || y1=="" || x2=="" || y2=="" || w=="" || h==""){
			alert("You must make a selection first");
			return false;
		}else{
			return true;
		}
	});
});

4. Finally it’s time to handle these new coordinates and generate our new cropped thumbnail.

if (isset($_POST["upload_thumbnail"])) {
	//Get the new coordinates to crop the image.
	$x1 = $_POST["x1"];
	$y1 = $_POST["y1"];
	$x2 = $_POST["x2"]; // not really required
	$y2 = $_POST["y2"]; // not really required
	$w = $_POST["w"];
	$h = $_POST["h"];
	//Scale the image to the 100px by 100px
	$scale = 100/$w;
	$cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
	//Reload the page again to view the thumbnail
	header("location:".$_SERVER["PHP_SELF"]);
	exit();
}

That is pretty much it, and all it took was 2 javascript files! Take a look at the demo and download a copy to see the full working code.

So far we have tested it in FireFox v2, Internet Explorer 6 and 7 with pretty good results. (Let us know if you find any issues with other browsers.)

The demo

Click here to see it in action

Download

Click here to download v1.0 [JPG ONLY]
Click here to download v1.1 [JPG ONLY]
Click here to download v1.2 [JPG, GIF, PNG]

169 Responses to “PHP & jQuery image upload and crop”

  1. How to set default crop size? For example, I’m need thumbnails 240×90 and any another size.

  2. There is a huge bug in this application around the extension. When the page loads the first time the extension is blank (“”). Now the line:

    $large_image_location = $upload_path.$large_image_name.$_SESSION[‘user_file_ext’];

    sets the image to have no extension. So the image name will be resize_21357153 (no extension). Then when you start saving the image there is a line:

    $large_image_location = $large_image_location;

    This will save the image without extension and your application will fail to load the image on refresh because it is looking for an image with extension.

    The solution to the problem is to change:

    $large_image_location = $large_image_location;

    to

    $large_image_location = $upload_path.$large_image_name.”.”.$file_ext;

  3. hi.. v1.2 worked properly but after 1hour i tried it again. It wont works please solve this issue…

  4. There’s similar jquery plugin that have resize and rotation along with the crop function: https://github.com/andyvr/picEdit

  5. I need to change thumbnail with and height when select main image. May I know how to do that? I don’t need fix thumbnail size.

  6. Any idea how to realize a free definable rectangle (via mouse) instead of a fixed aspect ratio?

  7. Could please any buddy make code for me once I have saved image if after some time I again call the save image and reedit it with crop function and again want to save it how it would be possible?

  8. Excellent script. Works great except that I cannot get it to work in Firefox. I can get the image, show the large and thumbnail images, but cannot draw the box over the large image to make the thumbnail selection.

    Anyone come across this and if yes, can you share the solution.

    Thanks
    Grant

  9. Am I wrong on this. It looks like the script takes the tmp file and uploads it to the large file location and also to the thumbnail file location. Once the image is cropped, then the thumbnail file is updated using the chmod command to reflect what the user wanted cropped. Is it possible to create a tmp file for the cropped image and only after accepted write it to a permanent file.

  10. It’s very Useful code.But I’ve changed the directory path to C:upload_pic its not working properly. Can u give any idea?

  11. Very useful indeed. Thanks a lot for sharing

  12. Hello! great script so far. Is there any way to display right away after you upload the image the dotted square that you are supposed to move around and resize to create the cropped image? It only shows up if you actually drag inside the image. There are lots of people that would be like “now what should i do and why it says i cant save the file” .. So if they see that dotted square right away at least it gives them a “hint” of what they have to do…. Anybody knows how to make it show up right away without having to drag around the mouse inside the original uploaded file? Thanks in advance

  13. what about transparent parts will be transparent after cropping too?

  14. You have to remove the added extension on these lines:

    $large_image_location = $large_image_location.”.”.$file_ext;
    $thumb_image_location = $thumb_image_location.”.”.$file_ext;

    It should be:

    $large_image_location = $large_image_location;
    $thumb_image_location = $thumb_image_location;

    :))

  15. I have the same problem too … has anybody found a solution for that? regards :)

  16. hi. such a nice script. just wanna ask how to add a default selection right away after uploading the image? thanks

  17. Hi,

    Nice script. Is there a way method to upload the image and resize the preview without overwriting it in a lower resolution?

    I’ve tried using max-width in CSS, but then the X and Y handlers no longer correspond correctly.

    Basically what I’m after is the same as the boxWidth property that Jcrop uses.

  18. I love this plugin but the problem I have had is file automatically adding the extension twice.

    For example I end up with resize_0123456789.jpg.jpg this means the image then doesn’t get displayed for the user to select a thumbnail area.

    Does anyone have any ideas why this could be happening?

    Thanks again for a great plugin

  19. i want to name output thumbnails according to value stored in variable in $gall instead of session keys. how can i do it?

  20. Try to insert a query string after the URL of both thumbnail and parent image. This hack worked for me… Excuse me my bad english, I’m BR.

  21. Hi and thanks for a wonderful bit of coding. It works great in all the Mac Browsers I tested it in. Safari 5.1.8, FF 19 & 20 and Chrome 26.

    I am a total beginner in PHP and was wondering if you can tell me how to attach the uploaded file to an email form on the same page. I read some stuff on locating files in a folder, but as the files keep getting renamed with a session value? (I think). I don’t know how to select them. Thanks

  22. Did the updated script we sent via email work for you?

  23. Hello, upload_pic folder has 777 permissions and the folder with the name of the user is created with 777 permissions assigned, but the images are stored in upload_pic and not in the user’s folder, I’ve been trying everything and I can not get the images are stored in the user’s folder.

    What else could I do?

    Thank you very much!

  24. try
    $username_get = $ _GET [‘username’];
    $upload_dir = “upload_pic/”.$username;

    However ensure before you do this, the “upload_pic” directory has sufficient permissions for the script to create the new folder.

    Let us know how you get on?

  25. I wish I could change the directory where the images, I would like to use a user variable to the directory having the name of the user, for example:

    $username_get = $ _GET [‘username’];
    $upload_dir = “upload_pic/'”. $ username_get. “‘”;

    Any idea?

  26. Hi Sam, the reason for the error is because of the php memory is not enough, please try adding this at the top of the script and see if that helps:

    ini_set(“memory_limit”, ‘-1′);

  27. There kinda an error.
    I placed these as my coodinates:

    $max_file = “10”; // Maximum file size in MB
    $max_width = “5000”; // Max width allowed for the large image
    $thumb_width = “1170”; // Width of thumbnail image
    $thumb_height = “458”; // Height of thumbnail image

    Because I wanted to take large images and resize them to 1170×458. But even when I crop the section..the result thumbnail is not the image I cropped. Please test or am I doing something wrong?

  28. Thanks for this script!!
    Is it possible to pre define the width and height as set values? Lets say making the crop in a 16:9 ratio and the output be 1170 x 458?

  29. Hi, you will need to update the plugin for imgareaselect (use the latest version available here: http://odyniec.net/projects/imgareaselect/jquery.imgareaselect-0.9.10.zip

    Then use the “hide” option as described in the plugin documentation to remove the selection on the image once you have completed your crop. OR use the “remove” option to completely remove the plugin from the image.

    Details can be found here: http://odyniec.net/projects/imgareaselect/usage.html#options

  30. Hi. I mean, after having selected the right area, I send the selection through an ajax call. Then I destroy the image node, but unfortunately, the plugin remains enabled: the area selector is still drawn on the screen (even if the image isn’t still there anymore). So I’d like to know how I can turn the plugin off.

  31. @facebook-1142851648:disqus what do you mean stop the plugin? Could you please explain?

  32. Hi, how do you stop the plugin ?

  33. I’d really like to have this as a WordPress plugin… with ability to add multiple instances per page, and work with use sessions

  34. thanx pal….nice one…

  35. “So far we have tested it in FireFox v2, Internet Explorer 6 and 7 with pretty good results. ”

    – Firefox 3.5.10, Opera 9.21, 9.51, 9.64 and 10.10, Safari 5.01 and Google Chrome are working fine in the Demo. Affirmative!

    Greetings,
    francky

  36. Hi,
    A wonderfull tool! And fast working too! :)

    Also a suggestion; line 11 under “2. Capture, rename and resize the uploaded file” reads:
    if (($file_ext!=”jpg”) && ($userfile_size > $max_file)) {
    $error= “ONLY jpeg images under 1MB are accepted for upload”;
    }

    I guess the error devil was walking by: the AND operator && should be the OR ||, otherwise a jpg of way > 1MB will pass easily. And a bmp of 20KB as well: the 2 conditions aren’t both true, so “no error”.
    In the jquery_upload_crop.zip I saw the upload_crop.php has the same && (line 103).

    Cordially,
    francky

  37. Exactly what I was looking for. Thank you!

  38. thanks for crop scripts but im also having the same issue. its not showing up with I.E 8 and the image came out wrong. any help?

  39. hello…

    thanks for the customized crop script. but it is not working in I.E-8. even image is not uploading. any help?

  40. very good script.
    I want to make 3 different height & width thumbnails and also want to show 3 previews.
    How this can be possible.

    Thanks!

  41. This is great solution.
    I am impressed with true solution.

  42. Is there any possibility to make a rectangle, not a square thumb with this or you have to modify the code?

  43. There’s another issue if the script is used in an iframe (Facebook) app, due to third party cookie restrictions in some browsers and some user settings.

    In this situation the script accepts an image upload only in the second attemp.

    If you are not concerned about session highjacking the following code additions makes the script more reliable. So the session ID can be handled without cookies.

    //Refresh the page to show the new uploaded image
    header(“location:”.$_SERVER[“PHP_SELF”].”?PHPSESSID=”.session_id( ));

    and the second change…

    //Reload the page again to view the thumbnail
    header(“location:”.$_SERVER[“PHP_SELF”].”?PHPSESSID=”.session_id( ));

  44. Script var working in my previous hosting but with the new one it doesnt. I select picture and hit upload but nothing is happening :(
    This two sites are mine and working on the same server.
    I couldnt understand the problem do you have any idea?

    phpinfo: http://www.gogoostick.com/
    uploadscript: http://www.eniyi5.net/crop2/index.php

  45. I have the same problem as Johnny. It works like a charm on one server, on one host, on the other – 1&1 running Plesk – I have the same prob,

  46. is it possible that the upload doesnt work in the downloadable file? I always get a time-out

  47. I have added the script and upload a picture. The picture saves to the upload directory but when the page refreshes there is no picture no error nothing. The image saves as resize_(randomnumbers).jpg.jpg

    When i upload another pic, the first pic is gone from the directory.

    So to rephrase. When i upload a pic, it uploads to the directory but no other actions take place on webpage. It just resets to what it originally looks like before an image upload. When i upload a second image it replaces the first in the directory with the same results on the upload page.

    Any help would be appreciated. I’m trying to build this thing now and will most likely move to a different script in 24 hours time. Thanks in advance!

  48. thanks for a script….i want the default selection on image…like when i upload an image, the script will automatically show a selection area on image…any idea how to do that

  49. Hi,

    I type all this for the second time – great product, just what we are looking for to allow end-users to easily upload and create thumbnail images.

    There is one problem with the thumbnail preview, when an area is selected the preview window sometimes displays the top portion of the main image invading the bottom portion of the preview (at a rate roughly double the rate of mouse drag).

    This seems only to happen when the image is quite deep, i.e. deeper than a 4:3 image

    PS – its annoying to lose an entire technical comment just because I missed the CAPTCHA!

  50. It could be very useful to have a parameter to change the aspect ratio of the cropped image (currently i can only get square thumbnails) or to specify a fixed width & height for the cropped image. Can anyone help with this? How can i change the script to work in this way?

    regards,

  51. @jj, it seems you may not have the GD2 graphics manipulation library, you can check this out looking at the output of phpinfo(); If the file does exist, it must be enabled in php.ini by adding the following lines in the file:

    [PHP_GD2]
    extension=php_gd2.dll

  52. Hi,

    This is perfectly useful.
    But I am getting an error message
    “Fatal error: Call to undefined function imagecreatetruecolor()”.
    Please help me to sort it out

  53. Oh man! This script is awesome!
    Congratulations, it helped me a lot!!!

  54. First, this is a pretty neat plugin. Thanks for it.

    I’m having a problem with implementation. As a standalone version, it works just fine, but when I incorporate it it into my website, it breaks. I think it has to do with the jquery-pack. It occurs to me it already includes jQuery 1.2.6. My site is heavily reliant on jQuery, and I use a lot of different plugins. I already use goggleapi for my whole site (maybe thirty pages.) Do you have a version that doesn’t include the jQuery library, and just the jQ scripts needed for your plugin?

    Again, thanks for the script, and in advance for any help you might give.

  55. Hi all,

    This is great!

    I was wondering if anyone knows how to create multiple versions of the cropped image for example: a large, medium and small version of the generated thumbnail?

    Much appreciated,

    Thanks! k

  56. Works really nicely. Thanks for sharing.

    Is it possible to let the user specify the dimensions of the cropped image? Say pass a width and height using an input alongside the upload form? That would be really cool.

  57. I want to have the original file name and extension. In this way now i can use only one image, that I always overwrite.
    Anyone can tell me how to fix this? (will this be in the newer version?)
    Just keep the file name

  58. thanks man, this is really a great script

  59. hi,
    thanks for the great script.

    my problem is eventough folder permissions on server is correct and script works flawless on a local test machine. i cant upload images(or cant create them) to server.

    any suggestions appreciated.

    have nice day.

  60. Thank you for your amazing script! It works like a charm. However, I came over with a problem when integrating it with a jQuery uploader rotine.

    Problem is that, after I upload the image and dinamically display it inside a div, the “preview” function seems not to find the large image, doing nothing with the thumbnail preview. Here is a bit of the code:

    onComplete: function(file, response){
    button.text(‘Upload’);

    window.clearInterval(interval);

    // enable upload button
    this.enable();

    // add file to the list
    $(”).appendTo(‘#example1 .files’).text(file);
    $(‘#origImage’).prepend(”);
    $(‘#thumbImage’).prepend(”);
    $(‘#thumbnail’).imgAreaSelect({ aspectRatio: ‘1:1′, onSelectChange: preview });

    }

    Note that I just call the “preview” function, after having completed the upload and displayed the image.

    Do you have any idea about what I am doing wrong on it? Any help would be very appreciated. Thank you!

  61. Excellent !!

    Thanks for a very nice post. I implemented this and found it quite simple and nice. Currently I am making some image gallery with CakePhp and eager to implement this feature.

    Please let me know if there is any implementation of this or any other feature in the same fashion with in CakePhp.

    Regards,

    Amjad Shaick

  62. @keithics, Yes you can, you would need to call the resize function to obviously resize the thumbnails in the various sizes you want.

    e.g. Call this function again but change the scale

    $scale = ($thumb_width)/$w;
    $cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);

    Saying this, you will have to give the new thumbnail a different name otherwise it will continue to get overwritten by the script. Remember to include the folder it has to be stored in too!

    $scale = ($thumb_width*2)/$w;
    $cropped = resizeThumbnailImage($upload_path.’my_new_thumbnail1′.$_SESSION[‘user_file_ext’], $large_image_location,$w,$h,$x1,$y1,$scale);

    This should give you a new thumbnail that is twice the size of the width set at the very top. Although this has not been tested.

  63. @Dac, please note all copyright notices must stay intact to use this solution

  64. nice script! thanks. Is there a way I can make multiple thumbnails? it would be great.

  65. Hi! I wonder if you’re allowed to use this solution on -any- website?

  66. this is a great script but i’m having a problem modifying it.

    how can i make the upload directory change dyamically based on a $_GET variable posted from a url, i have tried modifying $upload_dir = “../images/”.$_GET[‘folder’]; in image_functions but it posts it to the folder images/ instead ignoring the $_GET[‘folder’]

    Thanks

  67. When I upload an image it saves the image like resize_34242.jpg.jpg

    And i don’t want the images to be named resize_34242…
    i want my images to be named like resize_(original file name).(file extension)

    so much for the next version

    Can’t get it to work, because of the file extension problem, probably because PHP version… don’t know what version is on, probably 4.x

  68. @vishnu, if the large image is too big for the width then the thumbnail will not sit side by side. Either make the width of your site wider or make your larger image smaller to fit the screen.

    @helio, ensure the upload directory has write permissions (CHMOD 777), you can comment out the error reporting line to see what errors may be causing this error:
    change
    error_reporting (E_ALL ^ E_NOTICE);
    to
    #error_reporting (E_ALL ^ E_NOTICE);

  69. Hi,
    Sorry my English I’m from Brazil.
    I downloaded of this source and to test it I´m using easyPHP, when I run the source dont show any lines with errors of php but show the follows message

    “Unexpected Error

    Please try again
    Acesso Proibido! Você não tem premissão para acessar o objeto requisitado. Ele pode estar protegido contra leitura ou não ser legível pelo servidor. Se você acredita ter encontrado um problema no servidor, por favor entre em contato com o webmaster. Error 403 localhost 12/09/09 23:31:24 Apache/2.2.13 (Win32) PHP/5.3.0 ”

    What i need to do to use it without this problem??
    Thank
    Sorry my English but I want to try…

  70. Hi,

    I need uploaded image and croped image display side by side at the width I have set .

    At the moment when we upload a large image it is to large for the screen. and crop image go to beneth . 2 Images side by side would work better.

    Please help me

    regards

    vishnu

  71. in the upload_crop.php page please write as the Top of the Page another chunk of codes
    as below:

    ini_set(“memory_limit”, ‘-1′);

    It will create no problem when uploading a big image may be of 3.5 MB

  72. Hello!

    I love your script, ‘cos it very greatful not some than my knowlage :D
    I try to change the $_SESSION[‘random_key’] to my id, what i post it from GET variable, so i call the file like that: upload.php?imagename=xyz , but it doesn’t work if the page is reload. because the GET will be unset. After that i try change the header with $url = “upload.php?kepnev=”.$_GET[‘imgename’];
    header(“location:”.$url);
    but the variable did not exist here already.
    If you can please help me!

    Ahead thank you for the answers! (sorry for my poor english)

  73. hi , really liked this script, but i want to modify this and use it in my project, i just wanna save the croped image at last but not both image , so plese help me

  74. Hi,

    Its been really nice script and I used it with CakePHP framework. But I face one small but major issue with IE browser. When ever I upload new image, the page shows me the previous one as both main and thumbnail image. It seems come from cache as it show real image once i refresh the browser.

    I know there was below notice in your initial version.
    echo “NOTE: If the thumbnail image looks the same as the previous one, just hit refresh a couple of times.”;
    But its not in the latest on 1.2. I implement that too but still not succeed in resolving the problem

    Can you help me to resolve this issue?

  75. thank u ^ ^

  76. Thank you very much for the code, a donation has been sent.

  77. Pages do not load or refresh after a button click in IE. any work around for this?

  78. Well Script is good ..but i notice one problem :(

    Upload first image then drag mouse over main image..you will see crop image preview..now do not save it! just click again to upload another image and this time there will be a crop line on new image and javascript just stop working :(

    I am trying to reset everything before new image appear but didn’t get solution..

    Anyone can suggest solution ????

    Thanks,
    Saket

  79. @Ian, try clearing your cache and cookies, seems the session variable that holds the suffix of the image is not being overwritten.
    @Jim, you can adust the size of the crop by changing the thumbnail width and height.

  80. I love this plugin but the problem I have had is when I use it on my live server the resize image has the file extension twice, this wasn’t happening on my local machine.

    For example I end up with resize_0123456789.jpg.jpg this means the image then doesn’t get displayed for the user to select a thumbnail area.

    Does anyone have any ideas why this could be happening?

    Thanks again for a great plugin

  81. Really nice plugin… but it seems the final crop is always square….?!
    What is the sum of 0 and 4? Answer: 40!

  82. It’s a beautiful tool indeed. Now, I’d like to know if there is a way for:

    1) Save the thumb with the original image name.
    2) Delete the large image.

    The second task is easy for me to figure out how to achieve it, but the first one is beyond my actual skills.

    I’ll appreciate any idea.

    Cheers,

    Sergio

  83. this is a great script, thanks, only one problem, it is not working with the latest version of firefox, 3.0.12 on mac, it does work in Safari, and Opera however.

  84. I tried it by unzipping the files and putting them on a Web server.

    I changed the permissions so the file could be saved.

    It accepts the upload (I can see it in the directory).

    But after that it tries to download the PHP file instead of running the scripts to render a page for resizing.

    How to make the script actually work on your own server?

  85. Thanks for your post

  86. hey everone,

    great script thanks for that! I’m trying to implement it to my homepage. I have just one big issue: Can maybe someone help me to implement a “uploadbar” for the first image upload?

    I’m trying around since weeks without any success… if someone can help me out it would be really fantastic!

    Cheers,
    Rolf

  87. I’ve changed the max_upload on php.ini and it work greatly.

    Thank’s.

  88. @LP80 if the image size is greater than 2000px across php runs out of memory and crashes, try set the php memory limit higher than what you currently have? If you are still having trouble please contact us through our contact page.

  89. Hi,
    great work!!
    but i have a little problem…

    when i change $max_file value to 5, it should accept the files with a size<= 5Mb… but it doesn’t work

    and display the error message on line 200.

    the condition on line 182 isn’t filled ($_FILES[“image”] is empty), but i can’t explain the reason.
    the file size is lower than 5Mb, is a JPEG.

    Maybe the image size??

    can you help me?
    thank’s

  90. Hi , I have a question like Vega ….

    How to add a rand() to name , to upload non’stop the pictures…..
    If a have a portal and want to upload an image there is more images… so i need a random value be add’et to the name of file…
    when I make that in

    $large_image_name = “resized_pic.jpg”; // New name of the large image
    $thumb_image_name = “thumbnail_pic.jpg”; // New name of the thumbnail image

    and put :

    $large_image_name = rand().”resized_pic.jpg”; // New name of the large image
    $thumb_image_name = rand().”thumbnail_pic.jpg”; // New name of the thumbnail image

    The screen after upload no change… but the 1 file is Uploading ….
    so , how to make all work OK?
    Pleace help!

    P.S. Sorry my english is not so good, but I’m traing.

  91. Thanks for answering so promptly! I must be a bit thick though as I can’t find the line of code that you suggest replacing in the “upload_crop.php” file I downloaded (I am trying to use version 1.2 as I only want users to be able to upload a jpeg)…

  92. @Colin, please find the $thumb_image_name and replace the value of this with your ID, you may want to echo this to the page so that you can ensure it is the carrying the correct ID throughout the process of upload and crop.
    $thumb_image_name = $thumb_image_prefix.$_SESSION[‘random_key’];
    to
    $thumb_image_name = $ID;

  93. Great script. I’m very new to this and have one question. My application is allowing users to add a profile picture so they click in from profile page and a variable (ID number) is brought in. I want the thumbnail to be saved with the ID number as the filename. Which bit of the code do I need to modify to make this work??
    Thanks!!

  94. After having resized my picture, how could I avoid the sending of the original
    picture on the server?
    (I only need to save the resized picture)

    Thank you

  95. @Rariti the answers to your questions are as follows:
    1. Use a set width, along with the max-height variable. The max-height can be the actual height of the image, therefore should allow it to stretch in the way you need it to. However you will need to update the imgareaselect js file to the latest version which is available from the authors website. We unfortunately have not had time to update it in our package but will do soon.
    2. Please see the following comment Display cropping area on load

  96. Excellent Script. I am a designer and was working on my portfolio site. This script came in very handy. I no longer have to use Photoshop to resize tons of images.
    I successfully managed to make alot of tweaks to get it to integrate with my custom CMS. I added dynamic widths, heights that are pulled from the db. Works beautifully. Very well done, and was quite fun tinkering around with it.

    I do have two questions.
    1. How would I go about keeping a constant width and have the height be fluid, if the height is not set.
    2. On page load, how do I display the cropping area. Currently it does not show until you click the original.

    Thanks and again, wonderful script.

  97. @Ravi, please see the following comment

    Pre-defined crop area

  98. great script!

    Is it possible to have 3 pre-defined crop dimensions to crop an image? I’ve tried with 3 submit buttons, but got ‘Headers already set error’ and no empty PHP vars POSTED on UPLOAD form POST.

    tnx in advance

  99. Hi,

    Very good post. I have a small question regrarding the image crop selection. Can you provide a default crop area at the time of page load only. Which could be more use fill.

    I am asking because as i am in need of it. I want to have a default selected crop area.

    Thanks

  100. Hi,

    i want to save the imagename to a mysql database. I get the id from my record from the URL. so far so good. But after the upload, i lose the id.

    can anybody help me?

    i just started learning php.

  101. <img src=”myimage.gif?t=” . time()

  102. argh. i removed the < in front of the ?php because it doesn’t show up correctly. it should say this:

  103. whoops the above should say:

    <img src="" ...

  104. with reguards to the hitting refresh to update the picture because of old cache not being updated i would recommend the following code:

    <img src=””

    where $upload_file (for example) is “myimage.gif”. as mentioned above adding a random query string at the end of a image works, but only if the query is dynamic. this is why i opted for adding time() into the query above.

    hope this helps someone as the previous post about query string cache and this amazing code snippet from webmotionuk helped me. :)

  105. Hi, really nice piece of code you’ve written, thanks for sharing with us all!

    I’m having a problem with it however when integrating it into a CMS I have put together. Creating new thumbnails (and other assorted meta and publish infos) are straightforward enough, however I’m coming unstuck when I try to allow administrators the ability to update the thumbnail selection. I have managed to get the selection box to display correctly on my larger image, but I need this selection to be shown in the RHS thumb.

    However to do this, I need to fire some kind of onInit call to perform the same task as onSelectChange, (as currently it only fires after a mouse interaction, which of course moves the current selection).

    Is there any current way to do this?

    Thanks,
    Adrian

  106. @whiteknight, to get that sort of functionality you would need to write the code into a wordpress plugin.

  107. Hey,

    Nice script here, I havent tested it yet but I will soon.

    I know the feature saves the thumbnail etc but how could I get this to save into a users profile. Like have it intergrated with wordpress.

    So the user logs in > Uploads image > Crops image and hits save, then the thumbnail is saved for them in there user area?

    Can this be done?

    Thanks

    WhiteKnight

  108. Hi,

    Love this script, exactly what I need for a little web project. But… I have an odd problem. It doesn’t work unless I am logged on using my “root” user on my MacBook. I changed Apache2’s httpd.conf to refer to my own user, which got it to half work. The first page opens, allows me to select a pic to try to upload, but then I get a blank page without any error messages. Any idea what else would need to be changed for the script to run even when not logged in as root?? (this is on Mac OSX, Leopard)

  109. it ‘s ok! thank you very much!

  110. Look at lines 355 to 362,

    if(strlen($large_photo_exists)>0 && strlen($thumb_photo_exists)>0){
    echo $large_photo_exists.” “.$thumb_photo_exists;
    echo “< p >< a href=\"".$_SERVER["PHP_SELF"]."?a=delete&t=".$_SESSION['random_key'].$_SESSION['user_file_ext']."\" rel="nofollow">Delete images“;
    echo “< p >< a href=\"".$_SERVER["PHP_SELF"]."\" rel="nofollow">Upload another< / a >< / p >“;
    //Clear the time stamp session and user file extension
    $_SESSION[‘random_key’]= “”;
    $_SESSION[‘user_file_ext’]= “”;
    }else{

    replace with

    if(strlen($large_photo_exists)>0 && strlen($thumb_photo_exists)>0){
    echo “your photo was added, thank you”;
    //Clear the time stamp session and user file extension
    $_SESSION[‘random_key’]= “”;
    $_SESSION[‘user_file_ext’]= “”;
    }else{

  111. Hi, just a small question,
    when the picture is uploaded, i acces the page where i can resize it.

    Then i get the page where the resized pic is displayed and i can either delete it or uploaded another pic.

    On that page the full-size image and the resized image is show too.

    Is it possible to remove it on that page?
    I would like to replace the photographs by a message.
    for example: “your photo was added, thank you”

    thanks for your reply

  112. Is there a way to make this keep the original file name and then just add a “_thumb” to the thumbnail?

    Thanks..

  113. I havn’t been able to try this yet (at work), but i believe this is exactly what i’ve been looking for…

    If it is.. i’m pretty sure i’m going to name my first child after you..

    Lol Thanks!

    P.S. – My son/daughter will probably hate you, but i’m okay with that ;)

  114. Thanks for your plugin!

  115. Thx, I got it working, but i had to rewrite your code a bit.

    $(’#thumbnail + div > img’).css({
    width: Math.round(scaleX * 2000 / (2000/500)) + ‘px’,
    height: Math.round(scaleY * 1500 / (2000/500)) + ‘px’,

  116. @Oya, the reason the preview is not working as required, is because of the scaling. We’ve uploaded an image of 2000×1500, which is being scaled (not resized as in our script) to 500px, so now the preview is 4 times bigger width wise and 3 times bigger height wise.

    in the javascript function find the following
    $(‘#thumbnail + div > img’).css({
    width: Math.round(scaleX * 2000) + ‘px’,
    height: Math.round(scaleY * 1500) + ‘px’,

    and replace is with this this
    $(‘#thumbnail + div > img’).css({
    width: Math.round(scaleX * (2000/500)) + ‘px’,
    height: Math.round(scaleY * (1500/500)) + ‘px’,

    The 2000 and 1500 should be coming from php variables, so divide them by your $showwidth variable.

  117. Well, I tried a bit more, and I now have managed to get the savingprocess right. But I still have problems with the preview of the cropped image.

    I think I have two solutions:

    1. Learn how css crop works, then edit $(‘#thumbnail + div > img’).css({ in function preview(img, selection)

    2. When the image is uploaded, keep the fullsize and make a smaller picture with the width you use for the site. Then I use the smaller for the previewimage. I think this should work well.

    Anyone want to help me with either two?

    What i have done so far to get the script to save a correct crop of the fullsizeimage shown with a widthconstraint:

    Add a variable called $showwidth = 500; (500px in my case)

    above function preview(img, selection) i have added this: $forhold = $current_large_image_width / $showwidth ;?> (forhold is the norwegian word for proportion or something like that

    In function preview(img, selection):
    $(‘#x1′).val(selection.x1 * );
    $(‘#y1′).val(selection.y1* );
    $(‘#x2′).val(selection.x2 / );
    $(‘#y2′).val(selection.y2 / );
    $(‘#w’).val(selection.width * );
    $(‘#h’).val(selection.height * );

  118. As I was trying to write:

    The width of the original image is easy to edit.

    I think it would be a nice improvement of the script to implement this function, at least as an option. In my case, loadingtime of the image is no problem.

    If you add a variable for the maximum width of the original image (the witdh of the availible space in your site).

    And (as far as i can reckon) edit the coordinatecalculation in this function: function preview(img, selection).

    it should work.

    Unfortunately my skills in javascriptprogramming is pretty low, so i was not successful in editing the function.

    If anyone has a tips for this, it would be most appreciated, by me and most likely a lot of other users :)

    Ps. Check out my link to see it in action (You see the problem with the previewimage)

  119. @Oya, the reason we haven’t used the original image is because we wanted it to fit within our site’s width. So if a user uploads an image which is 1000pixels wide and our site only has say 600px of space, its not really going to work…The whole look and feel of the site will be broken because of that large image being displayed.

    There is no reason why you cannot edit the script to have it the way you want i.e. using the original image, the script is pretty well commented, and shouldn’t be difficult to achieve. There are also options to restrict the width of the original image (you can set this to as big as you want), so its fairly configurable. Although saying that, uploading very large images causes memory issues, so beware. (http://www.webmotionuk.co.uk/jquery-image-upload-and-crop-for-php/#comment-677)

  120. This is a pretty nice script. But what I don’t understand is why you don’t use the original uploaded image when you make the thumbnail. If the previewimage and the thumbnail are the same width, you get bad quality if you decrease the width of the crop.

  121. @ lapubell tankyou
    @ webmotionuk this tutorial fills a huge void in 80% off the webapps i’m aware. You Guys rock

  122. Great tool!

    @RUI, the original file name is stored in the variable $userfile_name. you can do anything you want to with that name.

    Just wanted to say thanks and I might bundle this up for a few upcoming projects. I’ll include a link to my version of this when I’ve kicked out all the bugs.

  123. Superb*****

    Now a newbie question
    I need to keep the original file name instead of $_SESSION[‘random_key’] how can i do this?

    Tanks in advance

  124. First off.. great script! One quick question. What would be needed to have the script make two new cropped images instead of just one. I’d like to try and get it to make a small version and large version of the cropped image. Thanks for making this available on your site! Great documentation as well.

  125. Hi, I’m testing this on an internal site and found that some users “ASSUME” that when they click “create thumbnail” that the program automatically does it. So I’m wondering if there’s a way to give people the option of either cropping a pic, or just having the program create a thumbnail automatically if they’re lazy of the original pic – how would this look in your program?

    Thanks for this wonderful tool.

    Paul

  126. Great Script, however I cannot for the life of me figure out the preview instance function.

    function preview(img, selection) {
    … $(‘#thumbnail + div > img’).css({
    width: Math.round(scaleX * ) + ‘px’,
    height: Math.round(scaleY * ) + ‘px’,
    marginLeft: ‘-‘ + Math.round(scaleX * selection.x1) + ‘px’,
    marginTop: ‘-‘ + Math.round(scaleY * selection.y1) + ‘px’
    });

    I want to place the preview image in a TD ( clients wishes, ugh). If the preview DIV gets placed into a TD, the onselect doesnt activate. I dont know much JS. Any ways I can make the function work for a TD?

  127. @craig, if you are not updating the images on a regular basis then delete the row and re-insert with the new data. Or depending on the database structure, if you are using a linking table then you can just delete the blob and re-insert into the linking table, and use an update statement for the main text content. if you require further help, please email us your code using our contact form, we will see what we can do.

  128. A superb script – thankyou. I had been trying to find a way to allow a user to crop an uploaded image prior to inserting it as a blob into a mysql database (I know it’s not a ‘good’ thing to do but it will only ever have 10 or so images stored at any one time) I have now done it using your code.
    The only outstanding issue I have is trying to edit an existing posted article. All I need to do is allow the user to change the photo stored as a blob for another one – not actually edit the blob. Have a play at http://www.motors4less.net/uploader.php if you wish. Image size limited . Just try editing an existing article and uploading a new image to crop.

  129. In case preview not at top and left,I dont know how to set default x1,y1 of preview, anyone tell me how to set it? Thanks a lot!

  130. Nice script …

  131. @Mark, to use a default image you will need to set the variable on line 61 to the name of your image as shown below:

    $large_image_name = “my_picture.jpg”;

    Ensure the image exists in the folder which is on line 59.

    $upload_dir = “upload_pic”;

    Your picture will then appear as default when you visit the page.

    NOTE: you will need to remove lines 153 to 155 (if (file_exists($large_image_location)) {…}) so that the default image is not deleted along with the thumbnail.

  132. Nice script, very cool.

    Like in the example, how can a default image be defined?

    Thanks

  133. @Mayya, thank you for your comments, you can adjust the proportion of the crop by selecting the size of the thumbnail your require. The proportions are automatically calculated. (1 : thumb_height/thumb_width)

    Please ensure you are using the latest version as this one only supports JPG images.

  134. Very nice application! Great Work!

    I’d really appreciate if you could add an option for image proportion because most of the time we don’t want an image with the same width and height.

    Keep it up.

  135. Very nice script!

    I just wonder if it is possible to make it “aspect free” ?

  136. BTW, great script!!!

  137. Hi, is there any possible way to make the size of selection a default size and in a way where users can move the selection around the actual image but not resize it?

  138. Really nice script, this is exactly what I was looking for. However, I was looking for at least three types of images(JPG, GIF, PNG). It dosen’t work for GIF and PNG. Could you please let me know if you have other version with this support? right now images are coming as black.

  139. This is a beautifully written script. I placed it on my website as a profile picture uploader. I was also wondering the same thing as Fredrik: how do I get this to work with a random image name?

  140. Really great script!
    Could you post the solution for a random filename that you mailed Frederik? I’ve been trying but I can’t get it to work. For example: How can I add a timestamp to the filename?

  141. EXACTLY what I was looking for, wonderful, perfect!

  142. Hello, how can I add a random(); to generate the name of the uploaded file…?
    Please emalil me someone at erisone(a)gmail.com, thanks!

  143. a question, as I do so that the thumbnail is a rectangle rather than a square thanks

  144. This is great, worked first time, and Long’s snippet is great too.

    Regarding the caching of images, just throw a random querystring on the image [ I just use ?t= ], and it won’t cache.

  145. great script! but it just dont work well on explorer 7. you need to hit refresh to see new image :( is there any solution for this issue? thank you

  146. This is an amazing script =) I love it… i had to change some few thing in it but i didnt get it to work with a random_key for the pic file name, so i just emailed the creator of the script…
    and then after 12hours the answer where in my inbox… and now it works perfecly finr!
    Thanks for a GREAT script, i be back for more =P

    //Fredrik, Sweden

  147. Thanks for your work, thats a really nice image facility. I am going to use this for our website for sure. keep up the great tutes and work!

  148. The http://www.webmotionuk.co.uk is cool site, good job

  149. I appreciate this… it is exactly what I was looking for!

  150. Your blog is interesting!

    Keep up the good work!

  151. Great stuff \o/
    Does anyone know how to make it works with Thinkbox jQuery ?
    That would be a way to use the crop when you do not have enough space on your page.

  152. Great work.. thanks.

  153. great job! Looking forvard for resize and rotate image functionality)

  154. Opps – too quick with the click button.

    I also wanted to say – great job. This is an excellent piece of work. :)

    Cheers

  155. I think you meant

    (($file_ext != "jpg") || ($userfile_size > $max_file))

    rather than

    (($file_ext != "jpg") && ($userfile_size > $max_file))

    Cheers

  156. Can you mod it to let users pick the cropping size from a drop down menu?

    thanks

  157. It is not trivial where you’ve got scaleX * 200 and scaleX * 300 when the Ferrari demo pic is 500 x 375. I figured that the proportions are the same, but couln’t you simplify it?

  158. Looks cool. Thanks :)

  159. I was thinking about having an image up load feature. Learning how to implement the upload feature was the fun part.

  160. Nice compilation, thanks, especially for JS part.
    As for PHP part, i wonder why not use php native imagesx() and imagesy() instead of writing new getWidth() and getHeight().

  161. Thanks, that did the trick. The problem was having “$(window).load(function () {“

  162. @chris,
    This is the original code:

    $(document).ready(function(){
    $('#asdf').slideDown('slow');
    });

    $(window).load(function () {
    $('#asdf img').imgAreaSelect({ maxWidth: 20, maxHeight: 20 });
    });

    Try this instead:


    $(document).ready(function(){
    $('#asdf').slideDown('slow');
    $('#asdf img').imgAreaSelect({ maxWidth: 20, maxHeight: 20 });
    });

    The imageareaselect will be called after the image is loaded, You could even put this into a click function as follows:

    $(document).ready(function(){
    $('#button').click(function() {
    $('#asdf').slideDown('slow');
    $('#asdf img').imgAreaSelect({ maxWidth: 20, maxHeight: 20 });
    });
    });

    Let us know how you get on.

  163. Here is the description of the problem

    http://www.nabble.com/imageAreaSelect-bug-td17861390s27240.html

    Im also experiencing problems if the img element does not have a width and height initially set. Why you might ask? Becasue I am loading content dynamically via AJAX calls

  164. @chris, why are you hiding the image in the first place? you may need to use livequery to pick up new elements introduced via JS. There is further information on the “image area select” plugin on the creators home page, see the link at the top of this page.

    Or give us a more detailed explanation of what you are trying to achieve, and if its relevant we can include it in the download.

  165. This plugin does not work if the img element was previously hidden and then displayed again via js. Seems to be a bug thats needs to be addressed

  166. @long, thats correct, your addition makes it that much more dynamic.

  167. text was cut off. correct change:
    $(‘#thumbnail’).imgAreaSelect({ aspectRatio: ‘1:<?php echo $thumb_height/$thumb_width;?>’, onSelectChange: preview });

  168. Thanks for the interesting script!
    However, it should be amended to read:
    line # 240 ($(‘# thumbnail ‘). imgAreaSelect)
    should be changed to:
    $(‘#thumbnail’).imgAreaSelect({ aspectRatio: ‘1:’, onSelectChange: preview });

Leave a Reply