Home >Backend Development >PHP Tutorial >ajax image upload and cut_PHP tutorial
允许用户以AJAX的方式上传图片
·允许用户选择图片的一定区域
·最后,提供一个裁减后图片的下载地址
我们将要用到三个文件
·index.php - 包含图片上传表单以及剪切界面
·upload.php - 提供上传功能
·crop.php - 提供剪切功能
从技术角度看,流程如下所示:
1.用户上传文件(index.php)
2.index.php将上传的图片POST到upload.php以处理上传图片程序,返回JSON数据包括图片名,长和宽。
3.根据JSON里的数据和innerHTML,我们将图片放在页面上
4.初始化javascript剪切工具
5.生成下载连接(crop.php)
让我们来看看index.php
index.php是我们的主要文件,用户通过他来上传和下载图片。
我们需要YUI提供的以下几个组件:
·yahoo-dom-event.js - 操作和解析DOM
·dragdrop - 基于图片剪切工具
·element - 基于图片剪切工具
·resize - 基于图片剪切工具
·connection - 为AJAX请求, 此例通过AJAX上传
·json - 解析JSON
·imagecropper - 我们最重要的工具
当然我们要用到 Yahoo combo handling并且加上上面提到的脚本和样式表:[code]
href="http://yui.yahooapis.com/2.5.2/build/resize/assets/skins/sam/resize.css"
/>
href="http://yui.yahooapis.com/2.5.2/build/imagecropper/assets/skins/sam/imagecropper.css"
/>
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">
[/code]然后用户一定会通过AJAX上传图片,所以我们在页面上加一个表单。[code]
AJAX upload
For AJAX uploads, see this tutorial on Code Central
Highly recommend this tutorial. I downloaded the sample code and changed it a little bit according to my own needs. Finally, I made a very good JSON object [uploader], which has only one method carry. The latter simply 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="" />';
photoshop.init(jsonData.image);
photoshop.getCroppedImage();
}
});
}
};
[/code]When the upload is completed, we get the JSON data mentioned earlier. [code]{"image" : "images/myimage.jpg", "width" : "500", "height" : 400}
[/code]This data and the container imageContainer we use to place the image will use yuiImg as the id[code]YAHOO.util.Dom.get
('imageContainer').innerHTML = '';[/code]It is very important to specify the length and width of the image, unless the image cropping tool is not working properly.
Next we will instantiate another JSON object photoshop, let's take a look.
Our photoshop object [code]photoshop = {
crop: null,
init: function(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 = 'download cropped image';
},
getCoordinates: function(){
return photoshop.crop.getCropCoords();
}
};
[/code]这个初始化方法初始化了yuiImg[code]photoshop.crop = new
YAHOO.widget.ImageCropper('yuiImg');[/code]我们同样要声明moveEvent方法,每当这个图片被移动或是被调整大小,我们就调用getCroppedImage这个方法来更新下载连接。[code]photoshop.crop.on
('moveEvent', function() {
// get updated coordinates
photoshop.getCroppedImage();
});
[/code]getCroppedImage方法将生成裁减后的图片地址。在PHP里实现,我们需要
·要处理的图片
·X,Y轴的坐标
·裁减后的图片长和宽
幸运的是,YUI的剪切工具里有一个方法满足了我们的需要,它就是getCropCoords()方法。所以,无论什么时候调用getCroppedImage方法,我们取到剪切图片的坐标,然后生成一个下载连接。[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 = 'download cropped image';
[/code]index.php的所有内容就在这里了。
upload.php[code]
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"}';
}
}
[/code]upload.php, as it is written, only parses images in jpg format, then generates a unique file name, places it in the images folder, and finally generates DOM operable JSON data. Of course, the images folder must be set to be readable and writable.
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 images through crop.php. First we get all the variables passed to us via 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 use the imagecopyresized method to generate the cut image. We add two header information, one tells the browser that this is a picture, and the other is a dialog box for saving the picture.