Ajax image upload and cutting

Source: Internet
Author: User

Allows users to upload images in AJAX mode
· Allow users to select a certain area of an image
· Finally, provide a download address for the cropped image

We will use three files.

· Index. php-contains the image upload form and cut interface
· Upload. php-provides the upload function
· Crop. php-provides the Cut function

From a technical perspective, the process is as follows:

1. The user uploads a file (index. php)
2. index. php POST the uploaded image to upload. php to process the uploaded image program. The Returned JSON data includes the image name, length, and width.
3. Based on the data in JSON and innerHTML, we put the image on the page.
4. Initialize the javascript cutting tool
5. Generate a download connection (crop. php)

Let's take a look at index. php.

Index. php is our main file. You can use it to upload and download images.

We need the following components provided by YUI:
· Yahoo-dom-event.js-operate and parse DOM
· Dragdrop-image cutting tool
· Element-image cutting tool
· Resize-image cutting tool
· Connection-is an AJAX request. In this example, it is uploaded through AJAX.
· Json-parse JSON
· Imagecropper-our most important tool

Of course, we will use Yahoo combo handling and add the script and style sheet mentioned above: [code] <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>
[/Code] then the user will upload the image through AJAX, so we add a form on the page. [Code] <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>
[/Code] click the upload button to activate the upload program. [Code] // add listeners
YAHOO. util. Event. on ('uploadclick', 'click', uploader. carry); [/code] we also need two containers:
· ImageContainer-include the image we uploaded
· DownloadLink-the download link will contain [code] <div id = "imageContainer"> </div>
<Div id = "downloadLink"> </div>
[/Code] the two containers will be updated through innerHTML later

AJAX Upload
For AJAX uploads, see the tutorial on Code Central.

I strongly recommend this tutorial. I downloaded the sample code and modified it a little as needed. Finally, I made a very good JSON object [uploader], which has only one method carry. The latter only submits form data to a specified URL. [Code] 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 = 'Src = "'+ jsonData. image +'" width = "'+ jsonData. width +'" height = "'+
JsonData. height + '"alt =" "/> ';

// Init our photoshop
Photoshop. init (jsonData. image );

// Get first cropped image
Photoshop. getCroppedImage ();
                        }
});
        }
};
[/Code] when the upload is complete, we get the JSON data we mentioned earlier. [Code] {"image": "images/myimage.jpg", "width": "500", "height": 400}
[/Code] this data and the imageContainer, the container for storing images, use yuiImg as the id [code] YAHOO. util. Dom. get
('Imagecontainer'). innerHTML = 'JsonData. image + '"width ="' + jsonData. width + '"height ="' +
JsonData. height + '"alt =" "/>'; [/code] it is very important to specify the length and width of the image, unless the image cutting tool is not working properly.
Next we will instantiate another JSON object photoshop. Let's take a look.

Our photoshop object [code] 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 ();
        }
};
[/Code] this initialization method initializes yuiImg [code] photoshop. crop = new
YAHOO. widget. imageCropper ('yuiimg '); [/code] we also need to declare the moveEvent method. Whenever the image is moved or adjusted, we call the getCroppedImage method to update the download connection. [Code] photoshop. crop. on
('Moveevent', function (){
// Get updated coordinates
Photoshop. getCroppedImage ();
});
[/Code] the getCroppedImage method generates the cropped image address. In PHP, we need
· Images to be processed
· Coordinates of X and y axes
· Cut Image length and width

Fortunately, one method in YUI's cut tool satisfies our needs. It is the getCropCoords () method. Therefore, whenever the getCroppedImage method is called, we obtain the coordinates of the cut image and generate a download connection. [Code] // 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> ';
[/Code] all the content of index. php is here.

Upload. php [code]
If ($ ext = "jpg "){
// Generate unique file name
$ NewName = 'Images/'. time ().'. '. $ ext;

// Upload files
If (move_uploaded_file ($ _ FILES ['uploadimag'] ['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 "}';
          }
}
[/Code] upload. as it writes, php parses only jpg images, generates a unique file name, places it in the images folder, and finally generates JSON data that can be operated by DOM. Of course, the images folder should be set to read/write.

Crop. php [code] // 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 );
[/Code] we can cut the uploaded image through crop. php. First, we get all the variables passed to us through AJAX. [Code] // get variables
$ Imgfile = $ _ GET ['image'];
$ CropStartX = $ _ GET ['cropstartx '];
$ CropStartY = $ _ GET ['cropstarty '];
$ CropW = $ _ GET ['cropwidth'];
$ CropH = $ _ GET ['cropheight '];
[/Code] we create two images, the original image and the cut image, and generate the cut image using the imagecopyresized method. We add two headers. One is to tell the browser that this is an image, and the other is to save the image dialog box.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.