jQuery+PHP实现上传裁剪图片

2020-05-17 06:23:50易采站长站整理

本文是一个简单的jquery图片预览+裁剪的例子,原理是在前端获取要裁剪的信息,如宽高比、裁剪坐标,上传图片之后在后端php进行切割

jquery代码(必须在最后面引入)


function showCutImg(showImg){
var showImg = $(showImg);
var changeInput = showImg.parents('.showImgDiv').siblings('.CutImage');
var size = changeInput.siblings('.imgCoord').attr('ratio').split('*');
var needWidth = size[0];
var needHeight = size[1];
var ratio = parseInt(needWidth)/parseInt(needHeight);
ratio = parseFloat(ratio.toFixed(2));
var thisFullDiv = showImg.parent();
var coordArr = changeInput.siblings('.imgCoord').val().split(',');

thisCutImgWidth = showImg.width();
thisCutImgHeight = showImg.height()

thisFullDiv.css('width',thisCutImgWidth);
thisFullDiv.css('height',thisCutImgHeight);

if((thisCutImgWidth/thisCutImgHeight)>=ratio){
var thisCutDivHeight = thisCutImgHeight;
var thisCutDivWidth = thisCutDivHeight*ratio;
}else{
var thisCutDivWidth = thisCutImgWidth;
var thisCutDivHeight = thisCutDivWidth/ratio;
}

var hideWidth = (thisFullDiv.width()-thisCutDivWidth)/2;

showImg.siblings('.hideImgLeft').width(hideWidth);
showImg.siblings('.hideImgRight').width(hideWidth);

var hideHeight = (thisFullDiv.height()-thisCutDivHeight)/2;

showImg.siblings('.hideImgTop').width(thisCutDivWidth);
showImg.siblings('.hideImgBottom').width(thisCutDivWidth);

showImg.siblings('.hideImgTop').height(hideHeight);
showImg.siblings('.hideImgBottom').height(hideHeight);

if(hideWidth>0){
var cutRatioX = thisCutImgWidth/hideWidth;
}else{
var cutRatioX = 0
}

if(hideHeight>0){
var cutRatioY = thisCutImgHeight/hideHeight;
}else{
var cutRatioY = 0;
}

var coord = needWidth+'#'+needHeight+'#'+(cutRatioX)+'#'+(cutRatioY);

if(coordArr!=''){
coordArr.push(coord);
}else{
coordArr = [coord];
}

changeInput.siblings('.imgCoord').val(coordArr);
$('.fullDiv').on('mousedown',function(e){
var me = $(this);

var changeInput = me.parent().siblings('.CutImage');

var index = me.attr('index');

var oldx = e.pageX;
var oldy = e.pageY;

var imgleft = me.children('.cutImg').position().left;
var imgtop = me.children('.cutImg').position().top;

var maxw = me.children('.hideImgLeft').width();
var maxh = me.children('.hideImgTop').height();

var goordArr = changeInput.siblings('.imgCoord').val().split(',');

var cutDivSize = goordArr[index].split('#');