php整合jcrop截取的上传头像功能
先来看看简单demo效果图
jcrop介绍jcrop是一个jquery插件,它能为你的web应用程序快速简单地提供图片裁剪的功能。
特点:
1、对所有图片均unobtrusively(无侵入的,保持dom简洁)
2、支持宽高比例锁定
3、支持 minsize / maxsize设置
4、支持改变选区或移 动选区时的回调(callback)
5、支持用键盘微调选 区
6、通过api创建互 动,比如动画效果
7、支持css样式
详细请自行百度jcrop
demo介绍这个demo选择整合了jcrop的截取图片插件,
上传图片还是使用file表单提交,php后台处理截图保存。
模块目录如下:
├─controller (控制器)
├─uppict (上传图片暂存位置)
├─userpic (截图保存位置)
└─views (视图)
视图代码croppic.php如下:
头像上传 .$_get['name'].' id=real_img style=max-width:90%/> .$_get['name'].' class=jcrop-preview float alt=preview />
'; } else { echo'
'; } ?>
上传文件:
允许上传的文件类型为:
视图js代码crop.js如下:
/** * 20150518 15:35 * author : ro * changedate: 20150519 10:25 * changecontext:修改计算坐标算法 *//***检测是否有选取一个区域**/function checkcoords(){ if (parseint($('#w').val())) return true; alert(请截取一个区域再提交保存!); return false;};jquery(function($){ var jcrop_api, boundx, boundy, // grab some information about the preview pane $preview = $('#preview-pane'), $pcnt = $('#preview-pane .preview-container'), $pimg = $('#preview-pane .preview-container img'), //这里获取的是装img的div宽高 xsize = $pcnt.width(), ysize = $pcnt.height(); //这里可以设置jcrop的属性, //如当改变截取区域时激活onchange: updatepreview动作等 $('#target').jcrop({ onchange: updatepreview, onselect: updatepreview, aspectratio: xsize / ysize },function(){ // 用jcrop的getbounds()方法获取真实尺寸 var bounds = this.getbounds(); boundx = bounds[0]; boundy = bounds[1]; // store the api in the jcrop_api variable jcrop_api = this; // move the preview into the jcrop container for css positioning $preview.appendto(jcrop_api.ui.holder); }); //更新jcrop预览视图 function updatepreview(c) { if (parseint(c.w) > 0) { //下面的比例是div的宽高与截图坐标比 var rx = xsize / c.w; var ry = ysize / c.h; //改变预览图的大小和显示位置 $pimg.css({ width: math.round(rx * boundx) + 'px', height: math.round(ry * boundy) + 'px', marginleft: '-' + math.round(rx * c.x) + 'px', margintop: '-' + math.round(ry * c.y) + 'px' }); var realwidth = $(#real_img).width(); var realheight = $(#real_img).height(); //记录位置和宽高 $('#x').val(math.round( c.x * realwidth / boundx )); $('#y').val(math.round( c.y * realheight / boundy)); $('#w').val(math.round( c.w * realwidth / boundx )); $('#h').val(math.round( c.w * realwidth / boundx )); } };});
控制器代码croppic.php如下: