PHP & jQuery image upload and crop


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

Before you start, ensure you have the following:

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

Our Requirement

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

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

  1. <form action=”my_upload.php” enctype=”multipart/form-data” method=”post”>
  2. Photo
  3. <input name=”image” size=”30″ type=”file”>
  4. <input name=”upload” value=”Upload” type=”submit”>
  5. </form>

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

  1. if (isset($_POST[“upload”])) {
  2.     //Get the file information
  3.     $userfile_name = $_FILES[“image”][“name”];
  4.     $userfile_tmp = $_FILES[“image”][“tmp_name”];
  5.     $userfile_size = $_FILES[“image”][“size”];
  6.     $filename = basename($_FILES[“image”][“name”]);
  7.     $file_ext = substr($filename, strrpos($filename, “.”) + 1);
  8.     //Only process if the file is a JPG and below the allowed limit
  9.     if((!emptyempty($_FILES[“image”])) && ($_FILES[“image”][“error”] == 0)) {
  10.         if (($file_ext!=”jpg”) && ($userfile_size > $max_file)) {
  11.             $error= “ONLY jpeg images under 1MB are accepted for upload”;
  12.         }
  13.     }else{
  14.         $error= “Select a jpeg image for upload”;
  15.     }
  16.     //Everything is ok, so we can upload the image.
  17.     if (strlen($error)==0){
  18.         if (isset($_FILES[“image”][“name”])){
  19.             move_uploaded_file($userfile_tmp, $large_image_location);
  20.             chmod ($large_image_location, 0777);
  21.             $width = getWidth($large_image_location);
  22.             $height = getHeight($large_image_location);
  23.             //Scale the image if it is greater than the width set above
  24.             if ($width > $max_width){
  25.                 $scale = $max_width/$width;
  26.                 $uploaded = resizeImage($large_image_location,$width,$height,$scale);
  27.             }else{
  28.                 $scale = 1;
  29.                 $uploaded = resizeImage($large_image_location,$width,$height,$scale);
  30.             }
  31.             //Delete the thumbnail file so the user can create a new one
  32.             if (file_exists($thumb_image_location)) {
  33.                 unlink($thumb_image_location);
  34.             }
  35.         }
  36.         //Refresh the page to show the new uploaded image
  37.         header(“location:”.$_SERVER[“PHP_SELF”]);
  38.         exit();
  39.     }
  40. }

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.

  1. $(window).load(function () {
  2.     $(“#thumbnail”).imgAreaSelect({ aspectRatio: “1:1”, onSelectChange: preview });
  3. });

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.

  1. function preview(img, selection) {
  2.     var scaleX = 100 / selection.width;
  3.     var scaleY = 100 / selection.height;
  4.     $(“#thumbnail + div > img”).css({
  5.         width: Math.round(scaleX * 200) + “px”,
  6.         height: Math.round(scaleY * 300) + “px”,
  7.         marginLeft: “-” + Math.round(scaleX * selection.x1) + “px”,
  8.         marginTop: “-” + Math.round(scaleY * selection.y1) + “px”
  9.     });
  10.     $(“#x1”).val(selection.x1);
  11.     $(“#y1”).val(selection.y1);
  12.     $(“#x2”).val(selection.x2);
  13.     $(“#y2”).val(selection.y2);
  14.     $(“#w”).val(selection.width);
  15.     $(“#h”).val(selection.height);
  16. }

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.

  1. $(document).ready(function () {
  2.     $(“#save_thumb”).click(function() {
  3.         var x1 = $(“#x1”).val();
  4.         var y1 = $(“#y1”).val();
  5.         var x2 = $(“#x2”).val();
  6.         var y2 = $(“#y2”).val();
  7.         var w = $(“#w”).val();
  8.         var h = $(“#h”).val();
  9.         if(x1==”” || y1==”” || x2==”” || y2==”” || w==”” || h==””){
  10.             alert(“You must make a selection first”);
  11.             return false;
  12.         }else{
  13.             return true;
  14.         }
  15.     });
  16. });

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

  1. if (isset($_POST[“upload_thumbnail”])) {
  2.     //Get the new coordinates to crop the image.
  3.     $x1 = $_POST[“x1”];
  4.     $y1 = $_POST[“y1”];
  5.     $x2 = $_POST[“x2”]; // not really required
  6.     $y2 = $_POST[“y2”]; // not really required
  7.     $w = $_POST[“w”];
  8.     $h = $_POST[“h”];
  9.     //Scale the image to the 100px by 100px
  10.     $scale = 100/$w;
  11.     $cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
  12.     //Reload the page again to view the thumbnail
  13.     header(“location:”.$_SERVER[“PHP_SELF”]);
  14.     exit();
  15. }

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

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

The demo

Click here to see it in action

Download

Click here to download

Source: http://www.webmotionuk.co.uk/php-jquery-image-upload-and-crop

Advertisements

One comment on “PHP & jQuery image upload and crop

  1. Tiếng anh không à. Bạn có thể dịch ra tiếng việt không . HIệu ứng này mình cũng định áp dụng cho hình ảnh tại kkfashion nhưng không biết làm thế nào

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s