前端
1,用到的插件jcrop,可以下载到本地,也可以用这个cdn
2,例子
页面添加代码
<img src="" alt="" name="target" id="target" style="max-height:230px;position:absolute;right:50px">
<input type="hidden" name="preview_img_x" value='0'><!--从离左侧多远的地方开始截图-->
<input type="hidden" name="preview_img_y" value='0'><!--从离顶部多远的地方开始截图-->
<input type="hidden" name="preview_img_h" value='640'><!--截多高-->
<input type="hidden" name="preview_img_w" value='480'><!--截多宽-->
封装好的js方法
function imgpreview(src){
//把上一个裁剪界面删掉.解决重新上传图,没有重新绘制裁剪界面的问题
if(window.jcrop_api != undefined){
window.jcrop_api.destroy();
}
var target = $('#target');
target.attr('src',src);
var imgurl = src;
var imgobj = new Image();
imgobj.src = imgurl;
imgobj.onload = function(){
//图的原始宽高
var width = $(this)[0].naturalWidth;
var height =$(this)[0].naturalHeight;
//显示时,最宽200px,最高 200/width * height
bili = 200/width;
var n_height = bili*height;
target.Jcrop({
setSelect:[
0,0,480,640 //初始选中区域
],
aspectRatio:3/4, //裁剪框的大小比例3:4,还有16:9啥的看自己需求
boxHeight:300, //绘制区域的最大高度
boxWidth:200, //绘制区域的最大宽度
onSelect:release, //裁剪框确定之后触发的函数
bgOpacity:0.8, //未选中部分的透明度
trueSize:[width,height] //图片的真实宽高
},function(){
window.jcrop_api = this;
});
}
}
function release(c){
console.log(c);
// $('#img1').css('bottom',c.y*bili);
// $('#img1').css('right',c.x*bili)
$('[name=preview_img_x]').val(c.x);
$('[name=preview_img_y]').val(c.y);
$('[name=preview_img_w]').val(c.w);
$('[name=preview_img_h]').val(c.h);
}
后端
把前端传过来的图片链接,x轴,y轴,宽高传给下面的方法就行了
/**
* 裁剪图片并保存到本地
*
* @param [string] $img 图片地址
* @param [int] $x x轴
* @param [int] $y y轴
* @param [int] $w 宽
* @param [int] $h 高
* @return void
*/
public function imgcropping($img,$x,$y,$w,$h){
$img_r = imagecreatefromjpeg($img);
$dst_r = imagecreatetruecolor(480,640); //图片最终大小
// echo $w,$h;exit;
imagecopyresampled(
$dst_r,
$img_r,
0,
0,
$x,
$y,
480,
640,
$w,
$h
);
imagejpeg($dst_r,'/home/wwwroot/video_mis/Runtime/jt.jpg',100);
}
2019-6-4补充
后端用到的这个函数imagecreatefromjpeg,不能处理png格式的图,注意!可以判断下图片的格式,选择对应的函数
$img_info = getimagesize($img)['mime']; //获取图片信息,用来判断图片格式
if(strpos($img_info,'png') !== false){
$img_r = imagecreatefrompng($img);
}else if(strpos($img_info,'jpg') !== false || strpos($img_info,'jpeg') !== false){
$img_r = imagecreatefromjpeg($img);
}
补充一张效果图