Home | Projects | Tutorials | Articles | live chat | Submit Project | Big Vote
 
Ajax Projects
.NET Frameworks
Java Frameworks
PHP Frameworks
Ruby Frameworks
Other Frameworks
Cool AJAX sites
Ajax Resources
Ajax Tools
JavaScript frameworks
Partners
ASP.NET Development

High quality ASP.NET development. see our portfolio

eBuddy

eBuddy articles and instant messenger tips

Stock Exchange Chat

Stock exchange community, chat room for each quote

Web 2.0 Sites

Web 2.0 reviews, articles, cool sites, screenshots, tips...

Self Imrovement

Videos for self improvement, self help, communication skills

Self Help

Articles for self improvement, self help, communication skills

Facebook Applications

Do you want to know the latest facebook applications?

bed sheets size guide

Visit Aqttan online store for famous egyptian cotton home textile products.

 Home /  Tutorials / Ajax image cropper-YUI- based

Ajax image cropper-YUI- based





The ImageCropper Control from the YUI library gives you an interactive interface for getting the dimensions to crop an image and using these dimensions in PHP, we can do some cropping.

Read The Full Tutorial.



This post will show you how to build an AJAX crop image tool using the image cropper control from YUI library and PHP.

Demo
Download sample file

The ImageCropper Control from the YUI library gives you an interactive interface for getting the dimensions to crop an image and using these dimensions in PHP, we can do some cropping.

The script we are going to build will

    * allow users to upload an image via AJAX
    * then allow them to select an area for cropping
    * lastly, provide a download link for the cropped image.

There are 3 files we are going to use

    * index.php - will contain the form for image upload as well as the cropping interface
    * upload.php - provides uploading functionality
    * crop.php - provides cropping functionality

From a technical point of view, the flow will be like this :

   1. user uploads jpg image (index.php)
   2. index.php then posts the image asynchronously to upload.php which will do the upload on the server, returning JSON data containing the image file name, its width and its height.
   3. with the JSON data and innerHTML we put the image in our page
   4. initialize the javascript cropping tool
   5. generate a download link (crop.php)


Let's have a look at index.php
The index.php is our main file where users will be able upload images and then download the cropped ones.

We'll need the following components from the YUI library :

    * yahoo-dom-event.js - for DOM manipulation and Event handling
    * dragdrop - dependency for the image cropper control
    * element - dependency for the image cropper control
    * resize - dependency for the image cropper control
    * connection - for AJAX requests, in our case for image uploads via AJAX
    * json - for parsing JSON data
    * imagecropper - our most important control

Of course we'll use Yahoo combo handling and add the js to our page along with the CSS needed for the above controls :

 
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.2/build/resize/assets/skins/sam/resize.css" />
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.2/build/imagecropper/assets/skins/sam/imagecropper.css" />
<!-- js -->
<script type="text/javascript" src="http://yui.yahooapis.com/combo?2.5.2/build/yahoo-dom-event/yahoo-dom-event.js&2.5.2/build/dragdrop/dragdrop-min.js&2.5.2/build/element/element-beta-min.js&2.5.2/build/resize/resize-beta-min.js&2.5.2/build/imagecropper/imagecropper-beta-min.js&2.
5.2/build/connection/connection-min.js&2.5.2/build/json/json-min.js"></script>
 

Next users must be able to upload images via AJAX, so we add a form to our page:

 
<form action="upload.php" enctype="multipart/form-data" method="post" name="uploadForm" id="uploadForm">
 Image :
<input type="file" name="uploadImage" id="uploadImage" />
<input type="button" id="uploadButton" value="Upload"/>
</form>
 

We have an onclick event to the upload button to fire the uploading process.

 
// add listeners
YAHOO.util.Event.on('uploadButton', 'click', uploader.carry);
 

We'll also need 2 containers :

    * imageContainer - will contain our uploaded image
    * downloadLink - will contain the download link

 
<div id="imageContainer"></div>
<div id="downloadLink"></div>
 

Both containers will be updated via innerHTML afterwards.

AJAX upload
For the AJAX upload, Code Central

has an excellent tutorial which I highly recommend. I took the code sample and modified it a bit to fit my needs. Finally I came up with a nice JSON object called uploader which has one method, carry. The latter just posts form data to a specified URL.

 
uploader = {
 carry: function(){
  // set form
  YAHOO.util.Connect.setForm('uploadForm', true);
  // upload image
  YAHOO.util.Connect.asyncRequest('POST', 'upload.php', {
   upload: function(o){
    // parse our json data
    var jsonData = YAHOO.lang.JSON.parse(o.responseText);
 
    // put image in our image container
    YAHOO.util.Dom.get('imageContainer').innerHTML = '<img id="yuiImg" src="' + jsonData.image + '" width="' + jsonData.width + '" height="' + jsonData.height + '" alt="" />';
 
    // init our photoshop
    photoshop.init(jsonData.image);
 
    // get first cropped image
    photoshop.getCroppedImage();
   }
  });
 }
};
 

When upload is complete, we get the JSON data we mentioned earlier on. For e.g :

 
{"image" : "images/myimage.jpg", "width" : "500", "height" : 400}
 

With this data and using innerHTML we update our imageContainer div to put our image which will have yuiImg as id :

 
YAHOO.util.Dom.get('imageContainer').innerHTML = '<img id="yuiImg" src="' + jsonData.image + '" width="' + jsonData.width + '" height="' + jsonData.height + '" alt="" />';
 

It's very important to specify the image width and height else the image cropper won't work.
Next we initialize another JSON object, photoshop which we'll have a look now.

Our photoshop object

 
photoshop = {
 image: null,
 crop: null,
 
 init: function(image){
  // set our image
  photoshop.image = image;
 
  // our image cropper from the uploaded image
  photoshop.crop = new YAHOO.widget.ImageCropper('yuiImg');
  photoshop.crop.on('moveEvent', function() {
   // get updated coordinates
   photoshop.getCroppedImage();
  });
 },
 
 getCroppedImage: function(){
  var coordinates = photoshop.getCoordinates();
  var url = 'crop.php?image=' + photoshop.image + '&cropStartX=' + coordinates.left +'&cropStartY=' + coordinates.top +'&cropWidth=' + coordinates.width +'&cropHeight=' + coordinates.height;
  YAHOO.util.Dom.get('downloadLink').innerHTML = '<a href="' + url + '">download cropped image</a>';  
 
 },
 
 getCoordinates: function(){
  return photoshop.crop.getCropCoords();
 }
};
 

The init function iniatializes the YUI image cropper from the uploaded image which has yuiImg as id.

 
photoshop.crop = new YAHOO.widget.ImageCropper('yuiImg');
 

We also subscribe to the moveEvent for the cropper since we'll need to update the download link for the cropped image. So whenever the image cropper is moved/resized, we call the getCroppedImage function.

 
photoshop.crop.on('moveEvent', function() {
 // get updated coordinates
 photoshop.getCroppedImage();
});
 

The getCroppedImage function will generate the download link for the cropped image. To do image cropping in PHP we'll need

    * the image we want to crop
    * the X,Y coordinates
    * height and width of the to be cropped area

Fortunately the YUI cropper utility has a function which will give us what we want, it's the getCropCoords() method. So, whenever the getCroppedImage function is called, we get the coordinates of the cropped area, build a URL and finally put the download link in our downloadLink container.

 
// get coordinates
var coordinates = photoshop.getCoordinates();
 
// build our url
var url = 'crop.php?image=' + photoshop.image + '&cropStartX=' + coordinates.left +'&cropStartY=' + coordinates.top +'&cropWidth=' + coordinates.width +'&cropHeight=' + coordinates.height;
 
// put download link in our page
YAHOO.util.Dom.get('downloadLink').innerHTML = '<a href="' + url + '">download cropped image</a>';
 

This is all we need for the index page.

upload.php

 
if(!empty($_FILES["uploadImage"])) {
   // get file name
 $filename = basename($_FILES['uploadImage']['name']);
 
 // get extension
   $ext = substr($filename, strrpos($filename, '.') + 1);
 
   // check for jpg only
   if ($ext == "jpg") {
        // generate unique file name
    $newName = 'images/'.time().'.'.$ext;
 
    // upload files
         if ((move_uploaded_file($_FILES['uploadImage']['tmp_name'], $newName))) {
 
          // get height and width for image uploaded
          list($width, $height) = getimagesize($newName);
 
          // return json data
             echo '{"image" : "'.$newName.'", "height" : "'.$height.'", "width" : "'.$width.'" }';
         }
         else {
             echo '{"error" : "An error occurred while moving the files"}';
         }
   }
   else {
       echo '{"error" : "Invalid image format"}';
   }
}
 

The upload.php file too is self explanatory, we check for a jpg image only, then generate an unique filename, put it in the images folder and finally build json data which we'll use for DOM manipulation. Of course the images folder must be writable by the web server.

crop.php

 
// get variables
$imgfile = $_GET['image'];
$cropStartX = $_GET['cropStartX'];
$cropStartY = $_GET['cropStartY'];
$cropW = $_GET['cropWidth'];
$cropH = $_GET['cropHeight'];
 
// Create two images
$origimg = imagecreatefromjpeg($imgfile);
$cropimg = imagecreatetruecolor($cropW,$cropH);
 
// Get the original size
list($width, $height) = getimagesize($imgfile);
 
// Crop
imagecopyresized($cropimg, $origimg, 0, 0, $cropStartX, $cropStartY, $width, $height, $width, $height);
 
// force download nes image
header("Content-type: image/jpeg");
header('Content-Disposition: attachment; filename="'.$imgfile.'"');
imagejpeg($cropimg);
 
// destroy the images
imagedestroy($cropimg);
imagedestroy($origimg);
 

Crop.php allows us to crop our uploaded image. First we get all the variables passed to us via the AJAX request,

 
// get variables
$imgfile = $_GET['image'];
$cropStartX = $_GET['cropStartX'];
$cropStartY = $_GET['cropStartY'];
$cropW = $_GET['cropWidth'];
$cropH = $_GET['cropHeight'];
 

Then we create 2 images, the original one and the cropped one, and use the imagecopyresized function to generate the cropped image. We add some header information to tell the world it's an image and prompt for a save dialog.

source: htmlblog

Related Tutorials

  • JSON in JAVA
    JSON is being widely used in Web Technology for data transfer in JavaScript. But with AJAX coming into picture JSON has become the most popular tool for sending data from remote page to the calling page.
  • JavaScript Ajax Wrapper
    The idea behind this post is not about calling a specific crmservice but a general idea of how you can facilitate calls to any webservice, whether it’s a custom one you built your self or one of crm’s existing services.
  • Build a Shopping Cart in ASP.NET
    Shopping carts are very important and can many times be the most intimidating part of building an e-commerce site. This tutorial will show how easy it can be to implement a shopping cart using ASP.NET.
  • AJAX Design Patterns
    how to design and build a complete site and not just some fancy little details like how to turn caching in AJAX off or how to create a fancy widget. To keep the tutorial readable, and to avoid having to implement low level functionality, IGÇÖm using the d
  • ASP.NET MVC and JSON
    In the AJAX community, JSON have become the preferred way of sending and receiving data. That’s not surprising since it’s lightweight, fast and easy to understand.
  • Creating an Autosuggest Textbox with JavaScript, Part 2
    In the first part of this series, you learned how to create type ahead functionality in a textbox, which presents the user with a single suggestion for what they've already typed. This article builds upon that functionality by adding a dropdown list of mu

Leave Your Comment

Name (Required)
Mail (will not be published) (required)
Website
Top Projects
e-messenger
MSN Web Messenger
ebuddy
MessengerFX
ILoveIM
AJAX file upload
You Tube
KoolIM.com
Ajax.NET Professional
Meebo
Tutorials
All Request, All The Time
Mocha UI - MooTools Canvas UI class
Building an AJAX chat with Parancoe and DWR
AJAX Security
Trying to be private in JavaScript
How to create the Google Suggest feature with ASP.NET 2.0
A new JavaScript mocking framework
AIM Express
Using Ajax in a JSF application - I
Faking an AJAX upload script