因为无法debug,断断续续几天才搞定
首先加载各个js和css,都在官网下载~
uploadify.css
jcrop.css
jquery.js
jquery.uploadify.min.js
jcrop.js
步骤:uploadify上传图片,得到图片路径在前台显示用户上传的图片赋给jcrop的id对象,裁剪后点击保存,将原始图片路径和各个坐标传给php,通过gd库实现裁剪图片的生成并保存到服务器!
1、uploadify的html
<form>
<div id="queue"></div>
<input id="file_upload" name="file_upload" type="file" multiple="true">
</form>
2、js部分,包括uploadify上传,缩略图呈现。
$('#file_upload').uploadify({
'swf' : 'support/uploadify/uploadify.swf',
'uploader' : 'uploadify.php',
'buttonText' : '+ 选择图片',
'fileTypeDesc' : 'All Files', // The description for file types in the browse dialog
'fileTypeExts' : '*.jpg; *.png; *.gif; *.JPG; *.PNG; *.GIF;',
'formData' : {},
'multi':false,
'removeCompleted' :true,
'onSelectError' : function() {
alert( file.name + ' 返回错误');
} ,
'onUploadSuccess':function(file, data, response) {//data uploadify.php返回数据;response为true false
$("#target").attr("src",data);//将用户上传的图片返回给前端,呈现出,省略其他部分代码
$("#cropphoto").show();
}
});
});
// Create a scope-wide variable to hold the Thumbnailer instance
$(function($){
var thumbnail;
// Instantiate Jcrop
$('#target').Jcrop({
aspectRatio: 1,
setSelect: [ 0, 0, 160, 160 ],//默认左上角开始的160*160大小截图
onSelect: updateCoords//更新坐标和大小,
},function(){
var jcrop_api = this;
thumbnail = this.initComponent('Thumbnailer', { width: 160, height: 160 });
this.ui.preview = thumbnail;
});
function updateCoords(c){
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
};
3、后台php实现将传过来的坐标和图片进行处理,并保存到服务器上。
html部分没有用form提交的格式,用的ajax,传入用户上传的图片路径、x、y、w、h
php代码:用了gd库,调用图像处理的几个函数,最后返回裁剪后图片的地址$newphoto;
$jpeg_quality = 90;
$src =$_GET["imgname"];//图片的路径地址
$img= imagecreatefromjpeg($src);
$dst = ImageCreateTrueColor( 160, 160 ); //创建大小为160的图片
imagecopyresampled($dst,$img,0,0,$_GET['x'],$_GET['y'],
160,160,$_GET['w'],$_GET['h']);//裁剪
$ext=pathinfo($src, PATHINFO_EXTENSION);
$photoname=pathinfo($src, PATHINFO_FILENAME );
$newphoto='upload/aaa.jpg'; //这是路径,不是文件名
imagejpeg($dst,$newphoto,$jpeg_quality);
imagedestroy($img);
imagedestroy($dst);
echo $newphoto
注意:1、如果发现图片生成但是是黑色底,基本上是imagecopyresampled这个函数有问题,确认get到值了没。因为创建图片的时候默认底色是黑色的
2、jcrop入了点坑,之前看到的缩略图基本用到了this.getBounds 但是看到新的jcrop的document中没有提到唉,是我没找到么。后来还是用demo的thumbnail来实现
3、对于上传图片过大需要调整大小的,这里没写,boxWidth什么的都没有用。求高人指点~