
<script type="text/javascript"> var jcrop_api, boundx, boundy; $(document).ready(function(){ $("#img").Jcrop({ setSelect:[0,0,150,150], onChange:updatePriview, onSelect:updatePriview, onSelect:updateCoords, aspectRatio:1 }, function (){ var bounds = this.getBounds(); boundx = bounds[0]; boundy = bounds[1]; } ); }); //............. function updateCoords(c) { $('#x').val(c.x); $('#y').val(c.y); $('#w').val(c.w); $('#h').val(c.h); var imgsrc = $("#img").attr("src"); $('#imgsrc').val(imgsrc); }; </script>
如上述js代码所示,onSelect:updateCoords,表示对图像上的区域选择完成之后,调用了updateCoords函数,将html中隐藏域的几个属性赋值,以便后台读取,下面是PHP代码:

<?php //根据updateCoords中传过来的值,取得图片url,选中区域的xy坐标及宽度W高度H $imgsrc = $_POST['imgsrc']; $x = $_POST['x']; $y = $_POST['y']; $w = $_POST['w']; $h = $_POST['h']; //通过url地址获取image对象 $img_r = imagecreatefromjpeg($imgsrc); //创建目标图像 $dst_r = ImageCreateTrueColor($w, $h); //创建一个临时图像,用于存放网页上进行切割操作的图像大小相等的一张图 //因为网页上上传的图片多有宽度和高度的设定,因此,width和height通常与原图的不相等 //下面的 imagecopyresampled方法是按照网页上显示图像的大小进行切割的 $temp = ImageCreateTrueColor(400,350); //取得原图的相关信息 $arr = getimagesize($imgsrc); //将原图缩放至网页上显示图片的大小 imagecopyresized($temp,$img_r,0,0,0,0,400,350,$arr[0],$arr[1]); //对$temp中的图像进行切割,并保存在 $dst_r中 //这个方法的意思是将$temp中图像中,起始坐标为$x,$y,宽度高度分别为$w,$h的区域, //复制到$dst_r中 imagecopyresampled($dst_r,$temp,0,0,$x,$y, $w,$h,$w,$h); header('Content-type: image/jpeg'); //直接在网页上输出切割好的图片 imagejpeg($dst_r,null,100); // NULL will output the image directly imagedestroy($img_r); imagedestroy($temp); imagedestroy($dst_r); exit;
imagejpeg($dst_r,null,100)是将图片直接输出,如果将null改为一个filename,即将图片保存为名为filename的图片,第三个参数是保存的图像质量,从1-100,数字越大质量越高,所占资源越大。