jQuery+PHP实现上传裁剪图片


Posted in jQuery onJune 29, 2020

本文是一个简单的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('#');

    $(document).mousemove(function(e){
     var newx = e.pageX;
     var newy = e.pageY;

     var movex = newx - oldx;
     var movey = newy - oldy;

     var x = movex + imgleft;
     var y = movey + imgtop;

     if(Math.abs(x)>maxw){
      if(x>0) x = maxw;
      if(x<0) x = -maxw;
     }

     if(Math.abs(y)>maxh){
      if(y>0) y = maxh;
      if(y<0) y = -maxh;
     }

     me.children('.cutImg').css('left',x+'px');
     me.children('.cutImg').css('top',y+'px');

     if(parseInt(maxw - x)>0){
      var cutRatioX = me.children('.cutImg').width()/parseInt(maxw - x);
     }else{
      var cutRatioX = 0;
     }

     if(parseInt(maxh - y)>0){
      var cutRatioY = me.children('.cutImg').height()/parseInt(maxh - y)
     }else{
      var cutRatioY = 0;
     }

     var cutImgPo = (cutRatioX) +'#'+ (cutRatioY);

     var coordVal = cutDivSize[0]+'#'+cutDivSize[1]+'#'+cutImgPo;

     goordArr[index] = coordVal;

     changeInput.siblings('.imgCoord').val(goordArr);


    });
   });


   $(document).on('mouseup',function(e){
    $(document).unbind('mousemove');
   });
  }



  $(".CutImage").change(function(){

   $(this).siblings('.imgCoord').val('');

   if($(this).prop('multiple')!=true){  //判断是否多文件上传
    var objUrl = getObjectURL1(this.files[0]) ;

    var showImgWidth = $(this).siblings('.showImgDiv').attr('showImgWidth');

    if(!showImgWidth)
    {
     showImgWidth = '150';
    }

    if (objUrl) {
      html = '';
      html += '<div style="border:1px solid #000;position:relative;z-index:2;overflow:hidden;cursor:move;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;" index="0" class="fullDiv">';
      html += '<div style="position:absolute;background:#ccc;top:0;z-index:4;opacity:0.95;left:0;right:0;margin:auto;" class="hideImgTop"></div>';
      html += '<div style="position:absolute;background:#ccc;bottom:0;z-index:4;opacity:0.95;left:0;right:0;margin:auto;" class="hideImgBottom"></div>';
      html += '<div style="position:absolute;height:100%;background:#ccc;left:0;z-index:4;opacity:0.95;" class="hideImgLeft"></div><div style="position:absolute;z-index:3;left:0;right:0;top:0;bottom:0;margin:auto;" class="cutDiv"></div>';
      html += '<div style="position:absolute;height:100%;background:#ccc;right:0;z-index:4;opacity:0.95;" class="hideImgRight"></div>';
      html += '<img style="position:absolute;z-index:1;width:'+showImgWidth+'px" onload="showCutImg(this)" class="cutImg" class="imgshover" src="'+objUrl+'" alt="图片加载失败" />';
      html += '</div>';          

      $(this).siblings('.showImgDiv').html(html);
    }

   }else{
    var objUrl = getObjectURL2($(this).get(0).files);
    if (objUrl) {

     var showImgWidth = $(this).siblings('.showImgDiv').attr('showImgWidth');

     if(!showImgWidth)
     {
      showImgWidth = '150';
     }

     var html = '';
     for(var i=0;i<objUrl.length;i++)
     {
      html += '<div style="margin-bottom:5px;border:1px solid #000;position:relative;z-index:2;overflow:hidden;cursor:move;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;" index="'+i+'" class="fullDiv">';
      html += '<div style="position:absolute;background:#ccc;top:0;z-index:4;opacity:0.95;left:0;right:0;margin:auto;" class="hideImgTop"></div>';
      html += '<div style="position:absolute;background:#ccc;bottom:0;z-index:4;opacity:0.95;left:0;right:0;margin:auto;" class="hideImgBottom"></div>';
      html += '<div style="position:absolute;height:100%;background:#ccc;left:0;z-index:4;opacity:0.95;" class="hideImgLeft"></div><div style="position:absolute;z-index:3;left:0;right:0;top:0;bottom:0;margin:auto;" class="cutDiv"></div>';
      html += '<div style="position:absolute;height:100%;background:#ccc;right:0;z-index:4;opacity:0.95;" class="hideImgRight"></div>';
      html += '<img style="position:absolute;z-index:1;width:'+showImgWidth+'px" onload="showCutImg(this)" class="cutImg" class="imgshover" src="'+objUrl[i]+'" alt="图片加载失败" />';
      html += '</div>';          //修改img标签的width样式可改变预览图大小

     }

     $(this).siblings('.showImgDiv').html(html);

    }

    //$('.fullDiv').css('float','left');
   }


  }) ;

  //建立一??可存取到?file的url
  function getObjectURL1(file) {
   var url = null ; 
   if (window.createObjectURL!=undefined) { // basic
    url = window.createObjectURL(file) ;
   } else if (window.URL!=undefined) { // mozilla(firefox)
    url = window.URL.createObjectURL(file) ;
   } else if (window.webkitURL!=undefined) { // webkit or chrome
    url = window.webkitURL.createObjectURL(file) ;
   }
   return url ;
  }

  //建立一??可存取到?file的url
  function getObjectURL2(file) {
   var url = new Array(); 
   if (window.createObjectURL!=undefined) { // basic
    for(var i=0;i<file.length;i++)
    {
     url[i] = window.createObjectURL(file[i]) ;
    }
   } else if (window.URL!=undefined) { // mozilla(firefox)
    for(var i=0;i<file.length;i++)
    {
     url[i] = window.URL.createObjectURL(file[i]) ;
    }
   } else if (window.webkitURL!=undefined) { // webkit or chrome
    for(var i=0;i<file.length;i++)
    {
     url[i] = window.webkitURL.createObjectURL(file[i]) ;
    }
   }
   return url ;
  }

html代码(这些代码要放在同一级)

<!-- 文件上传标签,添加class属性CutImage -->
<input class="CutImage" type="file" name="img" />

<!-- 传送图片裁剪比例等参数,要添加class属性imgCoord,ratio为裁剪后要保存的宽高width*height -->
<input ratio="100*100" type="hidden" class="imgCoord" name="imgCoord">

<!-- 图片预览,要添加class属性showImgDiv,showImgWidth表示预览时的宽度 -->
<div showImgWidth="100" class="showImgDiv"></div>

php代码

/*图片上传代码略 下面直接进行图片裁剪*/

/**
 * [cut_img 图片裁剪函数]
 * Author: 程威明
 * @param array $imgs   图片路径数组
 * @param array $info   裁剪信息?到M,包括裁剪后要保存的宽高、图片大小与裁剪开始坐标之比
 * @param bool $cover   是否覆盖原图,默认不覆盖
 * @return array    若覆盖原图返回裁剪数量,不覆盖返回图片路径组成的数组
 */
function cut_img($imgs=array(),$infoarr=null,$cover=false)
{
 if($infoarr==null) return $imgs;

 //判断是否为数组(必须是一个以图片路径组成的数组)
 $imgs = is_array($imgs)?$imgs:array($imgs);

 //把多个裁剪信息切成单个信息组成的数组
 $infoarr = explode(',', $infoarr);

 $save_file = array();

 $i=0;
 foreach($imgs as $file){

  //如果不覆盖原图,可重新定义图片保存路径
  if(false==$cover){
   $file = $file;
  }

  //把裁剪信息切割成数组,第一个为要保存的宽第二个为要保存的高,第三和第四个为图片宽高与裁剪起点的比例
  $info = explode('#', $infoarr[$i]);

  //裁剪宽高比
  $ratio = $info[0]/$info[1];

  //判断图片是否存在
  if(!file_exists($file)) continue;

  //获取图片信息
  $imgize = getimagesize($file);

  //图片宽度
  $width = $imgize[0];
  //图片高度
  $height = $imgize[1];

  //图片裁剪起点坐标
  $x = $info[2]==0?0:$imgize[0]/$info[2];
  $y = $info[3]==0?0:$imgize[1]/$info[3];

  //判断图片原宽高比与裁剪宽高比的大小
  if($width/$height>=$ratio){
   $width = $height*$ratio;//如大于即为裁剪宽度
  }else{
   $height = $width/$ratio;//如小于即为裁剪高度
  }

  //裁剪的??高不能超出?D片大小
  if(($width+$x)>$imgize[0]){
   $width = $width-($width+$x-$imgize[0]);
  }

  if(($height+$y)>$imgize[1]){
   $height = $height-($height+$y-$imgize[1]);
  }

  //创建源图的实例
  $src = imagecreatefromstring(file_get_contents($file));

  //??建一???D像
  $new_image = imagecreatetruecolor($info[0], $info[1]);

  //分配颜色
  $color = imagecolorallocate($new_image,255,255,255);
  //定义为透明色
  imagecolortransparent($new_image,$color);
  //填充图片
  imagefill($new_image,0,0,$color);

  //拷贝图片并保存成指定大小
  imagecopyresized($new_image, $src, 0, 0, $x, $y, $info[0], $info[1], $width, $height);

  //保存

  if(false==$cover){
   $file = rtrim(dirname($file),'/').'/c_'.basename($file);
   $save_file[] = $file;
  }

  imagejpeg($new_image,$file);

  imagedestroy($new_image);
  imagedestroy($src);

  $i++;
 }

 if(false==$cover){
  return $save_file;
 }else{
  return $i;
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

jQuery 相关文章推荐
jQuery插件FusionCharts绘制的3D环饼图效果示例【附demo源码】
Apr 02 jQuery
Jquery把获取到的input值转换成json
May 15 jQuery
jquery在vue脚手架中的使用方式示例
Aug 29 jQuery
使用vue与jquery实时监听用户输入状态的操作代码
Sep 19 jQuery
jQuery niceScroll滚动条错位问题的解决方法
Feb 03 jQuery
jQuery+css last-child实现选择最后一个子元素操作示例
Dec 10 jQuery
jQuery移动端跑马灯抽奖特效升级版(抽奖概率固定)实现方法
Jan 18 jQuery
Vue CLI3.0中使用jQuery和Bootstrap的方法
Feb 28 jQuery
JQuery属性操作与循环用法示例
May 15 jQuery
如何使用CSS3+JQuery实现悬浮墙式菜单
Jun 18 jQuery
jQuery实现颜色打字机的完整代码
Mar 19 jQuery
JQuery获得内容和属性方法解析
May 30 jQuery
jQuery Ajax实现Select多级关联动态绑定数据的实例代码
Oct 26 #jQuery
jquery使用FormData实现异步上传文件
Oct 25 #jQuery
jQuery+Datatables实现表格批量删除功能【推荐】
Oct 24 #jQuery
jQuery pagination分页示例详解
Oct 23 #jQuery
jquery.pagination.js分页使用教程
Oct 23 #jQuery
jquery分页插件pagination使用教程
Oct 23 #jQuery
使用jquery Ajax实现上传附件功能
Oct 23 #jQuery
You might like
PHP使用数组实现队列
2012/02/05 PHP
php通过字符串调用函数示例
2014/03/02 PHP
php获取域名的google收录示例
2014/03/24 PHP
php实现在多维数组中查找特定value的方法
2015/07/29 PHP
ThinkPHP项目分组配置方法分析
2016/03/23 PHP
php常用数组array函数实例总结【赋值,拆分,合并,计算,添加,删除,查询,判断,排序】
2016/12/07 PHP
Laravel框架模型的创建及模型对数据操作示例
2019/05/07 PHP
php+iframe 实现上传文件功能示例
2020/03/04 PHP
javascript 点击整页变灰的效果(可做退出效果)。
2008/01/09 Javascript
8款非常棒的响应式jQuery 幻灯片插件推荐
2012/02/02 Javascript
jquery 插件开发 extjs中的extend用法小结
2013/01/04 Javascript
jQuery焦点控制图层展示延迟隐藏的方法
2015/03/09 Javascript
浅析Node.js中的内存泄漏问题
2015/06/23 Javascript
浅谈Javascript实现继承的方法
2015/07/06 Javascript
javascript自定义in_array()函数实现方法
2015/08/03 Javascript
JQuery插件Marquee.js实现无缝滚动效果
2016/04/26 Javascript
JS 日期与时间戮相互转化的简单实例
2016/06/22 Javascript
详解Angular2响应式表单
2017/06/14 Javascript
js捆绑TypeScript声明文件的方法教程
2018/04/13 Javascript
vue 中滚动条始终定位在底部的方法
2018/09/03 Javascript
vue项目打包部署_nginx代理访问方法详解
2018/09/20 Javascript
Vue中Table组件行内右键菜单实现方法(基于 vue + AntDesign)
2019/11/21 Javascript
vue中实现弹出层动画效果的示例代码
2020/09/25 Javascript
python禁用键鼠与提权代码实例
2019/08/16 Python
基于python判断目录或者文件代码实例
2019/11/29 Python
通过css3动画和opacity透明度实现呼吸灯效果
2019/08/09 HTML / CSS
最新大学职业规划书范文
2013/12/30 职场文书
校园广播稿500字
2014/02/04 职场文书
标准化管理实施方案
2014/02/25 职场文书
工程资料员岗位职责
2014/03/10 职场文书
公司年会搞笑主持词
2014/03/24 职场文书
业务员自荐信范文
2014/04/20 职场文书
2014年财务个人工作总结
2014/12/08 职场文书
2015年小学教导处工作总结
2015/05/26 职场文书
新教师教学工作总结
2015/08/14 职场文书
【D4DJ】美少女DJ企划 动画将于明年冬季开播第2季
2022/04/11 日漫