PHP & jQuery image upload and crop v1.1
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
Due to popular demand, further updates have been made to this script, to allow upload of JPG, GIFs and PNG images! Same great functionality now even more useful.
Please note the old script is still available at PHP & jQuery image upload and crop.
If you are not familiar with the concept, it may be worth reading the old article first.
As with the previous script, ensure you have the following:
1. We will be using the session variable to hold the random file name (in our case the timestamp).
We are now also storing the file extension that is passed through the script, to ensure we are dealing with the right type of image.
//only assign a new timestamp if the session variable is empty
if (strlen($_SESSION['random_key'])==0){
$_SESSION['random_key'] = strtotime(date('Y-m-d H:i:s')); //assign the timestamp to the session variable
$_SESSION['user_file_ext']= "";
}
NOTE: Once the thumbnail is created we set the session variable to equal nothing, this will then allow a new image to be uploaded along with a new name.
2. Capture, rename and resize the uploaded file.
The validation section has also been updated and been made more secure by checking the mime type as well as the image extension.
foreach ($allowed_image_types as $mime_type => $ext) {
//loop through the specified image types and if they match the extension then break out
//everything is ok so go and check file size
if($file_ext==$ext && $userfile_type==$mime_type){
$error = "";
break;
}else{
$error = "Only ".$image_ext." images accepted for upload";
}
}
//check if the file size is above the allowed limit
if ($userfile_size > ($max_file*1048576)) {
$error.= "Images must be under ".$max_file."MB in size";
}
3. Same as before, we grab the coordinates using the imgAreaSelect plugin and send the details to the server.
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.
NOTE: Using the php calculation below makes the script that much more dynamic, all you now have to do is set the height and width of your thumbnail and the script will calculate the ratio/preview sizes for you! (Thanks to Long for the tip.)
$(window).load(function () {
$("#thumbnail").imgAreaSelect({ aspectRatio: "1:thumb_height/thumb_width", 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 = / selection.width;
var scaleY = / selection.height;
$('#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'
});
$('#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 = $thumb_width/$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();
}
Take a look at the demo and download a copy to see the full working code.
So far we have tested it in FireFox 2 and 3, Internet Explorer 6 and 7 and Safari 3.1.2 with pretty good results. The only issue we found was when uploading transparent gifs and pngs results in a black background.
Click here to see it in action
Click here to download v1.2 [JPG, GIF, PNG]
Click here to download v1.1 [JPG ONLY]
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
Awesome script, easy to use and easy to understand. Well done – thank you!
I’m also having problems in IE. The cropping rectangle does not appear by default in IE even though it is set to appear and works fine in Firefox. I’ve found that refreshing the browser can suddenly make it appear in IE!
Hi,
My goal is to have a default selection box (dotted rectangle) visible when the user uploads an image, and have the thumbnail preview show the default selected area by default. I want to size the default selection as a square, with a side being equal to the shorter of the length and width of the original image.
I’m able to create this default selection correctly. However the thumbnail preview does not show this by default. It shows the top left portion of the original image (100px * 100px).
If I use my mouse to click on the selection and move it around, as soon as I move it the preview “snaps” to correctly show the selected area. From this point on it works as expected. So my only issue is getting the default preview to accurately reflect the default selection.
Thanks for this great script. I am having a small problem where I can’t upload jpeg images. If I add the mime types and extension for jpeg then it works but I cant then upload jpg files. Please can someone point me in the right direction?
Thanks
Hi there,
currently using this wonderful script.
how can i make it work with jpg and jpeg.
If i change line 44 as above it only allows jpeg
All the best from Holland
What do you do if the image the person uploads is a wide rectangle, but the marquee is a square. Then the user can only upload a small part of the original image. Can you make it so their is white around the image or something to allow the user to select some white and some of the rest of the image in order to get more of the image but keep the dimension proportional?
Steve
Hi, I can’t figure out where I can set the thumbnail size.
these are my values for thumb width & height:
$thumb_width = “250″; $thumb_height = “265″;
the preview is absolutely fine but the uploaded thumb has a width of 100px and a height of 106px … so the ratio is fine, but how can I manage it to get a width and height of 250x265px?
I’ve tried to set the values here:
$cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,250,256,$x1,$y1,$scale);
but nothing changed … so where can I set the final width & height of the thumb?
THX!
Forty
On line 44 where it has
$allowed_image_types = array(‘image/pjpeg’=>”jpg”,’image/jpeg’=>”jpg”,’image/jpg’=>”jpg”,’image/png’=>”png”,’image/x-png’=>”png”,’image/gif’=>”gif”);
replace it with
$allowed_image_types = array(‘image/pjpeg’=>”jpg”,’image/jpeg’=>”jpg”,’image/jpg’=>”jpg”,’image/pjpeg’=>”jpeg”,’image/jpeg’=>”jpeg”,’image/jpg’=>”jpeg”,’image/png’=>”png”,’image/x-png’=>”png”,’image/gif’=>”gif”);
Notice the inclusion of the mime type and the jpeg suffix, This should fix your problem.
This fails in the case of image/jpeg, because $file_ext is then jpeg and $ext is jpg, so an error occurs…
187 //loop through the specified image types and if they match the extension then break out
188 //everything is ok so go and check file size
189 if($file_ext==$ext && $userfile_type==$mime_type){
Hi!nice work!
i’ve some trouble:the behavior of the script is random, somtimes it works, sometimes it just upload the photo without let me crop it.
Any guess?
Thanks
to me the cropping doesnt appear in firefox
plus if you want to upload a file larger than 500px (even if you modified the size to bigger already), you get a time-out when trying to upload (which is really weird)
I use Firefox and uploaded it to my own site, but I get a time-out when I try to upload the file. The file is also not stored on the server.
I get this error message in FF: The connection to the server was reset while the page was loading.
@Longboard, you correct in both your comments many thanks for spotting this (OOPS!!), just shows you cannot assume what people would do when using such an application.
In first case where there is a duplicate file extension, you are absolutely right in checking for file extension first. However, it would probably best to hide the upload form once the user has uploaded an image to ensure this does not happen regardless of the check being there. @Johnny, Longboards suggestion below would do the trick.
We will be updating this script in the coming month and if there are any other requests please let us know via the comments section on the following page: JQuery / PHP Upload and Crop – Feature Request
Another bug.. there is a devision by zero if no area is selected an you try to upload the thumbnail.
insert….
if ($w == 0) {
$error = “Please select an image area.”;
}
else {
before….
//Scale the image to the thumb_width set above
$scale = $thumb_width/$w;
and after
//Reload the page again to view the thumbnail
header(“location:”.$_SERVER["PHP_SELF"]);
exit();
insert….
}
So the user gets an error message what to do…
There’s an error in the php part concerning uploads. It is not possible to upload another photo if one was already uploaded in the same session.
Upload generated a image file with duplicated extensions. e.g. photo.jpg.jpg
And only the first uploaded images was displayed.
Try this.. in the .php. Replace:
$large_image_location = $large_image_location.”.”.$file_ext;
$thumb_image_location = $thumb_image_location.”.”.$file_ext;
with
if ($_SESSION['user_file_ext'] == “”) {
$large_image_location = $large_image_location.”.”.$file_ext;
$thumb_image_location = $thumb_image_location.”.”.$file_ext;
}
Nice script.. thank you….
Can this be modified to allow the user to upload more than one file at a time?
@Le, the code already resizes the original image on upload, to further reduce the size, you could call the thumbnail function giving specific height, width, and x1, y1 values
# $scale = 100/$NEW_w;
# $cropped = resizeThumbnailImage($NEW_thumb_image_location, $large_image_location,$NEW_w,$NEW_h,$NEW_x1,$NEW_y1,$scale);
Obviously there will be more tweaks needed but this will point you in the right direction.
Hi, your code is AWESOME!
I’m trying to figure out how to get the the code to automatically create a thumbnail on upload instead of having the user manually configure(which I want to leave optional). Could you point me in the right direction?
Thanks!
lateNIGHT i have the same question, but tomorrow ill try to make it work, JC says that he could so maybe we could too
PD: An example with mysq and PHP ill be very usefull.
Hi. I want ask if somebody have this script conected to the database.
You choose image from database crop it and save thumbnail location to database.
how can i store the original image on the server? next to the resized and the thumbnail. i am desperately searching for a solution. thanks. flo
Thank you! I’m new to php and this has been a wonderful introduction. I’ve enjoyed reading and playing with such a nice script!
I’ve got it working with MySQL to make a gallery of sorts.
Script works great, except for in IE (primarily IE8). Has anyone found a fix for IE 8 yet?
Hello
I have a problem with cropping the images. the parameters that i sending to function that crops the image (resizeThumbnailImage) are correct, but the cropping is not correct
What can be the problem? everything looks correct
Thanks a lot. Great script
Nice, but no work in ie6… =\ i know it is dead, or will dead, but some clients keeping using the DEVIL ie6 *cry* , but NICEEEE WORK!!!!
Hello everyone.
The script is fantastic, but there is a problem.
By uploading files with jpeg extension crashes.
Any suggestions?
Excuse my bad English!
Awesome man!
Congratulations, good work.
A couple of people have asked about saving the created thumbnail location into a MySQL database. Has anybody got this working? And if so, would you mind sharing here what you did to get it working?