Finally we had some time to create a full jquery image upload and crop script for php. This latest script is based on the first few versions of PHP & jQuery image upload and crop.
To upload the image using the one-click upload plugin, crop it using the image area select plugin, save the selected thumbnail and then display the final result. That should be fairly straight forward!
Well thanks to the above plugins it is!
Breakdown
Uploading the file
The jquery one-click upload plugin allows the use of a link or image or button to call the “file browse” window without the need for the “file” input type. Meaning we can make it look “pretty” however we didn’t really bother but you can if you wish. The usage of this plugin is similar to the jquery ajax() function as you can see from the below.
The plugin works by creating and submitting a hidden form with the correct “enctype” something which is not possible using the basic jquery ajax() function.
var myUpload = $('#upload_link').upload({
name: 'image',
action: 'image_handling_file.php',
enctype: 'multipart/form-data',
params: {upload:'Upload'},
autoSubmit: true,
onSubmit: function() {
//do something when the form is submitted
},
onComplete: function(response) {
//do something with the result
}
});
Few things to note: name: ‘image’ - this is the name of the file that is passed to the script below. action: ‘image_handling_file.php’ - this is the script that will handle all of out image uploading. params: {upload:’Upload’} - this is for any additional information that may be required in the script above. onSubmit: function() - when the “hidden” form is submitted, a function will be executed. onComplete: function(response) - when the process is complete we recieve the data back from the script which is stored in the variable called “response”.
Once the file has been uploaded, we will pass the file name through the onComplete: function(response), and load this response into an empty div. At the same time we activated the image area select plugin. NOTE: this must be done only after the image has loaded otherwise the cropping functionality will not work.
Cropping the image
This part as usual just grabs the coordinates of the area required and passes it to the image handling script using the jquery ajax function
$.ajax({
type: 'POST',
url: 'image_handling_file.php',
data: 'save_thumb=Save Thumbnail&x1='+x1+'&y1='+y1+'&x2='+x2+'&y2='+y2+'&w='+w+'&h='+h,
cache: false,
success: function(response){
//do something with the result
}
});
The response from this script will be the final resulting thumbnail. That is really all there is to it…
The PHP
We are not going to go into the php side of things here as it has been covered in the previous 2 articles. The files in this project are the same as before but have now been split to allow the dynamic capability.
Here is a break down of the files that are now required.
index.php - this contains all the javascript functions and is the file used to upload/crop/view the images.
image_handling.php - this file processes the upload, resizes the image and deletes images if required.
image_functions.php - this file holds the variables and functions to make the whole process possible.
Within the “index.php” and “image_handling.php” files there is an include statement, please ensure this points to exactly where the “image_functions.php” file is on your server!
As with our latest version of the upload and crop script this one also supports upload and cropping for JPG, GIFs and PNGs.
Demo
NOTE: Only JPGs that are below 10kb in size are allowed for upload in the demo! The upload folder is cleared every few minutes of all images.
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.
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.
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.
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.)
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.
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.
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.
2. Capture, rename and resize the uploaded file. (We also provided a set name for the uploaded file.)
if (isset($_POST["upload"])) {
//Get the file information
$userfile_name = $_FILES["image"]["name"];
$userfile_tmp = $_FILES["image"]["tmp_name"];
$userfile_size = $_FILES["image"]["size"];
$filename = basename($_FILES["image"]["name"]);
$file_ext = substr($filename, strrpos($filename, ".") + 1);
//Only process if the file is a JPG and below the allowed limit
if((!empty($_FILES["image"])) && ($_FILES["image"]["error"] == 0)) {
if (($file_ext!="jpg") && ($userfile_size > $max_file)) {
$error= "ONLY jpeg images under 1MB are accepted for upload";
}
}else{
$error= "Select a jpeg image for upload";
}
//Everything is ok, so we can upload the image.
if (strlen($error)==0){
if (isset($_FILES["image"]["name"])){
move_uploaded_file($userfile_tmp, $large_image_location);
chmod ($large_image_location, 0777);
$width = getWidth($large_image_location);
$height = getHeight($large_image_location);
//Scale the image if it is greater than the width set above
if ($width > $max_width){
$scale = $max_width/$width;
$uploaded = resizeImage($large_image_location,$width,$height,$scale);
}else{
$scale = 1;
$uploaded = resizeImage($large_image_location,$width,$height,$scale);
}
//Delete the thumbnail file so the user can create a new one
if (file_exists($thumb_image_location)) {
unlink($thumb_image_location);
}
}
//Refresh the page to show the new uploaded image
header("location:".$_SERVER["PHP_SELF"]);
exit();
}
}
3. Now that the image has been uploaded and saved to our folder we can use the “Image Area Select” plugin to crop our image.
It basically provides the coordinates to the server to handle the crop.
x1, y1 = coordinates of the top left corner of the initial selection area
x2, y2 = coordinates of the bottom right corner of the initial selection area
width = crop selection width
height = crop selection height
There are a number of options with this plugin which you can see using the link above. We opted for an aspect ratio of 1:1 (height and width of 100px) along with a preview of what we are actually going to crop.
Lets break it down, we first set the imgAreaSelect function to the image we want to crop, i.e. the one we just uploaded. As you can see, the aspect ration is set to 1:1, which means we are going to get a square selection. The “onSelectChange” is a callback function which runs the preview function when a change is made to the crop.
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.
This function is not really required, but helps by checking to see if the user has made a crop selection. In our case it is a required step. The form is submitted if the values exist, i.e. a selection has been made.
$(document).ready(function () {
$("#save_thumb").click(function() {
var x1 = $("#x1").val();
var y1 = $("#y1").val();
var x2 = $("#x2").val();
var y2 = $("#y2").val();
var w = $("#w").val();
var h = $("#h").val();
if(x1=="" || y1=="" || x2=="" || y2=="" || w=="" || h==""){
alert("You must make a selection first");
return false;
}else{
return true;
}
});
});
4. Finally it’s time to handle these new coordinates and generate our new cropped thumbnail.
if (isset($_POST["upload_thumbnail"])) {
//Get the new coordinates to crop the image.
$x1 = $_POST["x1"];
$y1 = $_POST["y1"];
$x2 = $_POST["x2"]; // not really required
$y2 = $_POST["y2"]; // not really required
$w = $_POST["w"];
$h = $_POST["h"];
//Scale the image to the 100px by 100px
$scale = 100/$w;
$cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
//Reload the page again to view the thumbnail
header("location:".$_SERVER["PHP_SELF"]);
exit();
}
That is pretty much it, and all it took was 2 javascript files! Take a look at the demo and download a copy to see the full working code.
So far we have tested it in FireFox v2, Internet Explorer 6 and 7 with pretty good results. (Let us know if you find any issues with other browsers.)