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.
<form action="my_upload.php" enctype="multipart/form-data" method="post">Photo <input name="image" size="30" type="file" /> <input name="upload" type="submit" value="Upload" /></form>
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']= ""; }
2. Capture, rename and resize 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(); } }
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 <strong>".$image_ext."</strong> 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. 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.
Update: 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!
$(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 = 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. 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.)
Change Log
- v.1.2
- Upload different types of images, JPG, GIFs and PNG
- The image upload error check has been fixed (thanks to DevWooty)
- v.1.1
- Upload images and have a random file name (this fixes the caching issue some of you have had)
- Error check
- v.1.0
- Initial plugin
Great work.. thanks.
Thanks a bunch for this piece…one problem though, how d i make it work on mobile devices?
Thanks sir, this work and I can save the image to database… 🙂
Next tutorial, please write about croping using cropie.js… heheh
in above code all variables and functions are showing undefined,is requried to add any header files,please suggest some idea.
how to add watermark
Hi,
can i change selector like horizontal.
Now Image selector increase rectangle. but i want to selector horizontal for cover pic,
can i change this setting.
I want to add watermark in this plugin it is possible
This is an “IMAGE UPLOAD and CROPPER” not an image manipulation script. Look into Image Majic or other software to do the other changes.
What code i want to display the image, when i refresh click url the image lost…help me to solve this issue.
i worked with this script to fit my project… and it works well on my local server… but not working on ipage server… what am i missing?
Great work. Works Excellent..
nice article
Hi,
Can this plugin worked in mobile device ?
Can you tell me device compatibility of this plugin?
Thanks,
I get the uploaded and resized photo on display with the preview square but not presenrted with cropping mechanism. Any reason ?
it crop tool does not work when implement at codeigniter
Hey Buddy , Worked your script . thank you for this . keep sharing
Worked wonders! Easily customisable too!
Excellent.. and thank you for the script.
Great work!
After a few goes, the script started to mess up… uploading images with 2 extensions (image.png.jpg), and not allowing me to select the thumbnail.
If anyone else has this problem, I added ‘session_destroy();’ to the end of the script, after the last ‘}’ which seems to have solved it.
Thanks.
Andy.
I cannot crop the image sometimes….plz help anyone???
I have a strange problem.
Same script is working on one website and is not working on another.. on the same server with the same settings of the server. Also same directory and same write permission of directory…
Do you know where should be the problem? T
Thanks. Stelian
i found the problem … cookies… but how can we fix this problem forever? 🙂
I want to add more input field such as text, text area to this image upload form, but when I do so, this form don,t submit the values that the added field hold , anyone can tell me why.
Hey there!
Love your guys script but I’m coming up with an issue, after I implemented everything I found that I have to select the image twice to upload then it will go to the crop step and then can save. Has any one else experienced this issue with having to upload the image twice before being able to move on?
Thanks
B
I want to generate thumbnail what user select cropping area so it’s not give perfect result when i upload more than 2000px width image.
It is not working in firefox after a few attempts, but its working in chrome and IE. I tried delete cookies and clear cache. But not working in Firefox .
no sorry, it was cookie issues with my session, its working now 🙂
Great Information sir.
thanks
oh…thanks a lot…..excellent brother……..this is very helpful for me…..
How to set default crop size? For example, I’m need thumbnails 240×90 and any another size.
hi.. v1.2 worked properly but after 1hour i tried it again. It wont works please solve this issue…
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.
ver 1.2 not working in firefox
There are some tutorials out there for the same. But this was well described and simple. Thanks, it really helped.
What a magnificent script, congratulations, works just great!!!
Any idea how to realize a free definable rectangle (via mouse) instead of a fixed aspect ratio?
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?
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
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.
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?
Very useful indeed. Thanks a lot for sharing
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
Is there a way to like assign a different directory? Something like
/ public_html / root / new_folder_instead_of_default_folder / test /
And is there a way to assign an actual file name to the uploaded file?
such as “123.jpg”
And
if “123.jpg” exist then allow a new upload or a crop of the image. If
“123.jpg” doesn’t exist, then allow upload. I’ve tried to do these 2
things, but I keep getting errors.
what about transparent parts will be transparent after cropping too?
Hi. Many thanks for sharing.
I’m moving to the new version and I’d like to know if it’s possible to alter the code for:
-to keep the original name of the image (prefix+originalName) instead the session ID.
-to create not one but two thumbs with two different sizes
Thanks
I have had this problem:
Action: Images selected for upload and crop
Message type: “no files selected” (spanish version)
Result: Image stored in “upload_pics”, but the crop system doesn’t appears.
Browser: Google Chrome Versión 28.0.1500.72 m
FIX: delete the cookie (I did use the extension “Edit This Cookie 1.2.1” for Chrome)
Seems there is a problem with the “Delete Images” rutine (see below message by Velvet for a solution)
Hope this help someone.
Cheers
I have the same problem with firefox 24.0 and safari!
I tried the two solutions you explain, but it doesn’t work.
Actually, I have two problems: crop system doesn’t appear
and the image is stored as “something”.jpg.jpg
For the second issue I read I have to empty cache. But I have to do it every time and it’s not practical…
Anyone have an idea? Please help me!!
hi. such a nice script. just wanna ask how to add a default selection right away after uploading the image? thanks
Hello and thank you very much. I was wondering if there is a way to have the preview image dynamically size to the crop window? I dont want to have to set oth the height and width of the preview image before the user selects what they want to crop. Is this possible?
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.
Is there a way to disable the resizing of the uploaded file but still giving a smaller window in which to crop the image. Raising the following variable: $max_width , allows me to do the first, the second is a little trickier. I tried giving the images a style with a max-width. But that messed up the preview.
I’m basically trying to create the normal functionality, only without losing the high resolution.
Any ideas on how to achieve this?
Hi Timo, have you found an answer for this yet!? I am also trying to figure out a way to make the visible full size image being cropped smaller, but only visibly on the screen, without actually resizing the image to a smaller width height.
I tried setting width and height to the image being cropped but then when i crop, the thumbnail doesnt match the area i selected to crop. please, if anyone can offer any help i would greatly appreciate it!!
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
I have the same problem too … has anybody found a solution for that? regards 🙂
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;
:))
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;
i want to name output thumbnails according to value stored in variable in $gall instead of session keys. how can i do it?
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
How can I up the output compression quality? Thanks very much for this. Works great and helped my team with photos for a blog.
There is a line for resizing JPG that takes a quality parameter (line 125):
imagejpeg( $newImage, $thumb_image_name, 90 );
Change the 90 to 100 for 100% quality.
Is there any particular reason this script would add the file extension twice?
I’ve recently been testing the php section of the code and have noticed that I am getting files names such as resize_.png.png
Seems the upload process was completed but then the crop was abandoned which has resulted in the session not being cleared.
is there a possibilty to integrate with virtuemart for uploading image in a print on demand website ? thx
I had to modify the delete function to clear the session variables, otherwise the upload can stop working without returning any error message. What ends up happening is you hit “Upload”, the images are uploaded, but you are not presented with the crop selection–instead you’ll be returned to the upload form.
if ($_GET['a']=="delete" && strlen($_GET['t'])>0){
//get the file locations
$web_image_location = $upload_path.$web_image_prefix.$_GET['t'];
$thumb_image_location = $upload_path.$thumb_image_prefix.$_GET['t'];
if (file_exists($web_image_location)) {
unlink($web_image_location);
}
if (file_exists($thumb_image_location)) {
unlink($thumb_image_location);
}
// Clear session variables - add to fix broken upload
$_SESSION['random_key']= "";
$_SESSION['user_file_ext']= "";
header("location:".$_SERVER["PHP_SELF"]);
exit();
}
I tried your solution, but it doesn’t work for me! is there any other way to fix it?
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?
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?
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!
Did the updated script we sent via email work for you?
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?
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’);
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?
Hi, how do you stop the plugin ?
@facebook-1142851648:disqus what do you mean stop the plugin? Could you please explain?
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.
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
I’d really like to have this as a WordPress plugin… with ability to add multiple instances per page, and work with use sessions
Love this image gallery!
thanx pal….nice one…
“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
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
Awesome script, easy to use and easy to understand. Well done – thank you!
Exactly what I was looking for. Thank you!
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?
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.
hello…
thanks for the customized crop script. but it is not working in I.E-8. even image is not uploading. any help?
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
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!
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
This is great solution.
I am impressed with true solution.
Is there any possibility to make a rectangle, not a square thumb with this or you have to modify the code?
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){
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.
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() );
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
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
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,
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)
is it possible that the upload doesnt work in the downloadable file? I always get a time-out
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.
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…
@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
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….
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!
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
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!
Can this be modified to allow the user to upload more than one file at a time?
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,
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
@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
Oh man! This script is awesome!
Congratulations, it helped me a lot!!!
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!
@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.
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.
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
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.
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.
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.
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
thanks man, this is really a great script
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.
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.
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:
o
nComplete: 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!
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
nice script! thanks. Is there a way I can make multiple thumbnails? it would be great.
@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.
Hi! I wonder if you’re allowed to use this solution on -any- website?
@Dac, please note all copyright notices must stay intact to use this solution
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
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
Script works great, except for in IE (primarily IE8). Has anyone found a fix for IE 8 yet?
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…
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
@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);
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!!!!
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
Hello everyone.
The script is fantastic, but there is a problem.
By uploading files with jpeg extension crashes.
Any suggestions?
Excuse my bad English!
Hello!
I love your script, ‘cos it very greatful not some than my knowlage 😀
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)
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
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?
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.
Awesome man!
Congratulations, good work.
thank u ^ ^
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?
Thank you very much for the code, a donation has been sent.
Pages do not load or refresh after a button click in IE. any work around for this?
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
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
@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.
Really nice plugin… but it seems the final crop is always square….?!
What is the sum of 0 and 4? Answer: 40!
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
I like this script and is very informative and customizable..but is ther a way to delete the original image or the image with resize prefix to be deleted as i would like to have only thumbnail image in my server –I am unable to locate the correct place to unlink the image so that I have only thumbnail image in my server folder…
Thank you in advance.
I want to be able to have the processed images saved to a different folder. I changes the path here:
//Image Locations
$large_image_location = $upload_path. $large_image_name. $_SESSION['user_file_ext'];
$thumb_image_location = $upload_path. $thumb_image_name. $_SESSION['user_file_ext'];
but it doesn’t work. Is there an easy way to save the uploaded file and the cropped file in different places?
Is there a way to only save the cropped file?
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.
I have the same problem as Dan.
I can’t upload picture with width bigger then 1000 px. I have blank page then. when I refresh site I see crop area but when I want save the thumb it doesn.t work 🙁
Plis help..
ops sorry.
Even if i add just a BOLD tag inbetween, the preview area dont work.
Hi there… i need some help.
Everything works perfectly fine but when i i want to start skinning the template by separating the big image and the crop preview by different table cell, the preview area stops working.
Eg:
<img src="" style="float: left; margin-right: 10px;" id="thumbnail" alt="Create Thumbnail" />
XXX
<div style="float:left; position:relative; overflow:hidden; width:px; height:px;">
<img src="" style="position: relative;" alt="Thumbnail Preview" />
If i place a text ( XXX ) inbetween the big image and thumbnail, it work but as long as there html tags in between, error is found.
Even if i add just a inbetween, the preview area dont work.
Any idea how i could resolved this?
i have a problem…
area-select-window is set on load. when i stretch the window, the selected portion is not getting cropped. its saves some other portion of the same image. but it shows correctly in the preview window.
it also works correctly when i dont stretch the window…
how to solve this??
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?
First off, must say that I love the script! It works just as expected, but there’s one extra thing that I think would be very helpful.
Cropping is restricted by the boundary of the picture. If you were trying to focus in on one part of the photo, you can only zoom so far.
Is it possible to zoom out passed the frame of the image? Maybe a white frame could be added to the resized image, so that the image itself is bigger allowing to zoom in farther???
Anyone know how I might achieve something like that?
Thanks for your post
This is a cracking script, however im trying to upload the image path into a Mysql field at the same time, so the database can call the image using the path.
Is this possible?
I basically have a profile script and the photo is stored with the records name, email, number. I have made the fields in the table but cant figure out how to insert an image path to call up, its driving me crazy!
Ive searched google and still looking for an answer, if I find out how to insert the image path into a table ill let you guys know, any help would be much appriecated!
Great tool…thanks..my images are not caching now 🙂
I said to myself I wasn’t going to write a comment because I hate writing comments asking for help, but I tried everything I thought of apart from… restart the browser! Obviously all the session variables etc. were still set to the old ways, so it was getting very confused. Seems to be sorted now.
What a great tool, keep up the good work.
Really don’t expect anybody to know this, but whatever – I got it working, just about, had a problem with directories (I changed them), and it was working. Change too many file directories, stopped working at all. Buggered up so downloaded it again and now the fresh version, without any of my modifications, doesn’t work.
Files upload, and I can see them in upload_pics, but the form doesn’t bring them back to crop them.
Any ideas?
Hi,
I am trying to implement your code , I have a list of profiles for which i need to upload images. I have successfully implemented the upload feature and thumbnail generation. Now the problem is when i delete the image for one profile and then come back and add an image for the same profile, it always displays the previous image (cache). This works fine in FF ,but IE is loading images from cache…any idea how to solve this. I have added no cache header to the page but still it is cachin the image..
Thanks
Pradish
Hello everyone,
Thank you for promoting this script, I really like… But I have one big issue, which I’m not able to figure it out, maybe someone of you guys can help me out.
In the first step of the script I’m trying to implement a “uploadbar” which shows the process of uploading the “big”-first image… Maybe someone can share an example with me or help me with some tips?
Thanks for that!
Rolf
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
Figured it out – it was obviously my mistake..
Thanks again for the great piece of code.
Peter
Hi,
Great script, thank you very much – actually it’s one of the best image upload scripts I’ve seen. However, I’m having little compatibility issues on IE8 and FF3.5.
on IE8 – works only in compatibility mode.
on FF3.5 – doesn’t get to the crop part at all.
I was wondering if anyone else is having similar issues?
Peter
Hi,
I think this is a very cool application but would like to tweak it a little bit. I would like not to have to upload the image before making the crop selection. I can get the image in the cropping area fine and the selection works perfectly but here’s the question:
How wolud I go about changing the php-script so that it uploads a file I specified in the form posted (not in a file-type input field but a hidden one)? And then does the same cropping as the original script, of course.
Thanks in advance!
Fredrik
I’ve changed the max_upload on php.ini and it work greatly.
Thank’s.
I believe I may have found a bug.
I set max_file to “5” and max_width to “640”
I then tried to upload a 4.5 MB JPG which then returns a blank page without the crop features. I hit the back button which then reveal the original image of 2304×3072 with the crop features but these don’t work.
I was just testing how a user might realistically upload a photo after directly docking their camera. I advise that you use this same test scenario to counter the bug.
Hi,
great work!!
but i have a little problem…
when i change
$max_file
value to 5, it should accept the files with asize<= 5Mb
… but it doesn’t workand 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
@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.
WOW!!!!!!!!!!!!!!
The best upload script ever, 100% customizable.
Here’s one contribution:
At the line where is the Image to Crop add “cursor:crosshair” at the style.
The changed version is:
<img src="" style="float: left; margin-right: 10px;cursor:crosshair" id="thumbnail" alt="Create Thumbnail" />
And it will show a cross when mouse is hover.
Thanks a lot
Higor
higorvaz@gmail.com
Thanks.
I wonder how I can crop image with different sizes.
Can anyone enlighten me how to do it?
@shin, you can crop at different sizes, however it will require you to edit the script to remove the elements that define the thumbnail size and replace it with your own. Also a preview may not be possible for images that do not have a fixed thumbnail height and width.
Do you know of a method to add text to uploaded images?
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.
Hi webmotionuk,
I have an issue with IE 6, when i upload an image for the first time, the cropping tool isn’t visible. After i close the window with your script and reopen >> reupload >> i can see the cropping tool.
This only appears in IE6 at the moment
Any advice??
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)…
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!!
@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;
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
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.
@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
Brilliant
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
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
@Ravi, please see the following comment
Pre-defined crop area
webmotionuk,
Does this PHP script work in safe_mode = ON?
@dydream, safe_mode must be off for this script to work.
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.
Thank you very much, it’s working perfectly on both IE & FF now!
Hi, I am trying to use this great plugin in a JQuery Dialog but I’m having issues with z-index of the selection div,
I tried (with no result):
$('.imgareaselect-outer').css(z-index:2000 !important;);
$('.imgareaselect-selection').css(z-index:2000 !important;);
Do you know a way to fix this please?
@Kyaan, your css command for jquery is incorrect, please see the jquery documentation on applying css to elements,
$(".my_element").css( "color", "#ffffff" )
Try
$(".my_element").css( "z-index", "200" )
<img src=”myimage.gif?t=” . time()
argh. i removed the < in front of the ?php because it doesn’t show up correctly. it should say this:
“
whoops the above should say:
<img src="" ...
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. 🙂
Thanks for the script … very useful!
I’m having an issue with the selection tool in IE7. I’m working off of your upload_crop_v1.2.php file “as is”. I was able to upload a photo, but when I go to make the selection, I get an error:
Line: 13
Char: 12949
Error: Invalid argument
Code: 0
URL: .../upload_crop_v1.2.php
Things are working fine in Firefox though. I also looked at your demo in IE7 and it works fine. Any ideas?? I could be overlooking something simple.
I’m using jquery-1.3.2.min.js and jquery.imgareaselect-0.8.js.
Very nice script…
I’m trying to do the same thing as huzzi – got the thumbnail overview loading up perfectly on load, but is there a way to ensure the thumbnail matches this on load (as opposed to on mouse interaction)?
Thanks,
Adrian
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
Nice script…
Can someone crop an image that is larger than the screen size?
Is it possible for someone to download what they just cropped?
Thanks,,,
AG
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
@whiteknight, to get that sort of functionality you would need to write the code into a wordpress plugin.
Brilliant, thanks so much.
Is it possible to make the thumbnail overlay visible on load?
thanks
@huzzi,
Find and change the following line
$('#thumbnail').imgAreaSelect({ aspectRatio: '1:1', onSelectChange: preview });
to
$('#thumbnail').imgAreaSelect({ x1: 120, y1: 90, x2: 280, y2: 210, aspectRatio: '1:1', onSelectChange: preview });
Obvioulsy the
x1,y1,x2,y2
values above are just an example and may not work on your image. Adjust as necessary.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)
it ‘s ok! thank you very much!
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
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 a > p >";
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{
it’s a mistake from me,sorry.
thank you for your fast reply
In script 1.0, it was possible to re-upload a file if the uploaded picture didn’t (on the screen you resize the pic.)
In 1.2 version, it seems this feature isn’t avaible anymore. How can i solve this problem? Thanks
@nicos, could you please specify again what it is you need, your comment doesn’t really make sense. in both scripts you are able to re-upload a new image once a crop has been made.
Is there a way to make this keep the original file name and then just add a “_thumb” to the thumbnail?
Thanks..
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 😉
It is wonderful. But we have one issue in IE 7. If we left double click on image instead of cropping area select then getting a JavaScript error “Invalid arguments”. But working fine with Firefox. Any idea to fix this issue.
Thanks in advance
Honish
hi, i tried to use it but after i load the image this is what i get “
Fatal error: Call to undefined function: image_type_to_mime_type() in c:/apache/htdocs/upload_crop_v1.2.php on line 5
”what am i doing wrong?
@munky, the
image_type_to_mime_type()
function is a built in PHP function more details can be found here image_type_to_mime_type, this function has been found to create problems in PHP versions older than 4.3.in our code, just above the image_type_to_mime_type function there is the following:
list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType);
change it to
list($imagewidth, $imageheight, $imageType, $bits, $channels, $mime) = getimagesize($image);
$imageType = $mime;
You will need to change it in both the image resize functions
starting line: 56 –
resizeImage()
function andstarting line: 97 –
resizeThumbnailImage()
functionHopefully that should do the trick.
Thanks for your plugin!
Unfortunately it does not work all that well on google chrome, it uploads the image but does not go tot the crop image part.
Great work all round chaps. Looks like it will be extremely useful.
Just one thing that I ask in ignorance. I am trying to get the name of the file to be the same as the original filename. I have located the variable (
$userfile_name = $_FILES['image']['name'];
) but I can’t for the life of me work out where I need to insert it to make it work. Please could someone help out as I’m tearing out what little of my hair I have left!!Many thanks in advance
@daemon & @nickstaw, thanks for the comments.
@nickstaw, you basically have to use the
$large_image_location
and set that to the original file name, however, you will need to pass this name throughout the script therefore saving the name of the original file in a session will do the trick.this is perfekt work..!!!
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’,
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({
infunction 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 thatIn 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 * );
@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.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)
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.
@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. (https://www.webmotionuk.com/jquery-image-upload-and-crop-for-php/#comment-677)
@ lapubell tankyou
@ webmotionuk this tutorial fills a huge void in 80% off the webapps i’m aware. You Guys rock
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.
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
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.
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
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?
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.
@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.
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!
Nice script …
@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.
Nice script, very cool.
Like in the example, how can a default image be defined?
Thanks
@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.
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.
Very nice script!
I just wonder if it is possible to make it “aspect free” ?
@Michal we will include your updated version in the download
@Dydream:
Please try the latest version (0.5.1), it should fix the problem.
Has anyone used this script in Konqueror (under Linux) ?
Michal’s Image Area Select plugin turns the large image black, and the crop are white during cropping.
never mind, I got it. it was working but my png file was not saved in ‘indexed’ so it wasn’t working before.
your script is so close to perfect for me. Can you help me take it one step further? Once the pic is uploaded and the user has selected the area they want to thumbnail, can you help me insert the ability to watermark it? (watermark will stay at 100 by 100 dimensions) Also, could I send the new filename into a mysql database? Please let me know how I can insert this into the script. Thanks
BTW, great script!!!
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?
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.
Just wanna let you know that I’ve been working on a WordPress function and your previous script was a BIG help for me. I’ll be checking out this new one and see what I can improve on.
I thank you very much!
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?
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?
EXACTLY what I was looking for, wonderful, perfect!
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!
a question, as I do so that the thumbnail is a rectangle rather than a square thanks
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.
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
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
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!
The https://www.webmotionuk.com is cool site, good job
I appreciate this… it is exactly what I was looking for!
Your blog is interesting!
Keep up the good work!
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.
Great work.. thanks.
great job! Looking forvard for resize and rotate image functionality)
Opps – too quick with the click button.
I also wanted to say – great job. This is an excellent piece of work. 🙂
Cheers
I think you meant
(($file_ext != "jpg") || ($userfile_size > $max_file))
rather than
(($file_ext != "jpg") && ($userfile_size > $max_file))
Cheers
Can you mod it to let users pick the cropping size from a drop down menu?
thanks
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?
Looks cool. Thanks 🙂
I was thinking about having an image up load feature. Learning how to implement the upload feature was the fun part.
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().
Thanks, that did the trick. The problem was having “$(window).load(function () {“
@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.
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
@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.
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
@long, thats correct, your addition makes it that much more dynamic.
text was cut off. correct change:
$('#thumbnail').imgAreaSelect({ aspectRatio: '1:<?php echo $thumb_height/$thumb_width;?>', onSelectChange: preview });
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 });