利用Javascript裁剪图片并存储的简单实现

 更新时间:2017年03月13日 11:18:21   作者:_construct  
裁剪图片对我们来说是再熟悉不过的了,最近工作中就又遇到了这个需求,所以想着干脆整理下来,方法大家和自己在需要的时候参考学习,所以这篇文章主要介绍了利用Javascript裁剪图片并存储的简单实现,后端PHP处理我用的是THINKPHP框架,需要的朋友可以参考下。

前言

就我而言,页面上的设计比较灵动的部分,其实不是很多,诸如滑动验证码,图片裁剪等比较好的交互设计。

从刚开始工作的时候,我就想把这些东西了解下,无奈一直没这个需求,乘着今天的空闲,研究了一下午,期间遇到了大大小小的问题,一直备受折磨,这其实也反映一个问题,我的

还是比较薄弱。

实现效果:

用户点击上传图片后,页面显示所上传的图片,并且出现裁剪框和两个预览区域,最后点击裁剪按钮保存裁剪的图片到服务器上。 

效果很简单,整个过程我遇到的两个难点,第一个是裁剪的JS效果,第二个则是图片数据的处理。 

对于第一个问题,我引用了网上的一个插件,就我感觉来说,裁剪过程用户的满意度只能算一般,因为它只能裁剪正方形区域,就算边框上有八个拉动设置,但是拉动框时还是按正方形缩放,就这点不太让我满意。

实现方法如下: 

以下是简单的页面设计:

<div style="float:left;"><img id="target"></div>
<div style="width:48px;height:48px;margin:10px;overflow:hidden; float:left;"><img style="float:left;" id="preview" ></div>
<div style="width:190px;height:195px;margin:10px;overflow:hidden; float:left;"><img style="float:left;" id="preview2" ></div>
<form action="{:U('/test/crop_deal')}" method="post" onsubmit="return checkCoords()" enctype="multipart/form-data" id="form">
<input type="file" name="file" onchange="change_image(this)">
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input type="submit" value="裁剪"/>
</form>

下面是JS代码:

function change_image(file){
var reader = new FileReader();
reader.onload = function(evt){
$("#target").attr('src',evt.target.result);
$('#preview').attr('src',evt.target.result);
$('#preview2').attr('src',evt.target.result);
// $('#target').css({"height":"600px","width":"600px"});
// 限制了大小会影响到截图的效果
};
reader.readAsDataURL(file.files[0]);

var jcrop_api, boundx, boundy;

setTimeout(function(){


$('#target').Jcrop({
minSize: [48,48],
setSelect: [0,0,190,190],
onChange: updatePreview,
onSelect: updatePreview,
onSelect: updateCoords,
aspectRatio: 1
},
function(){
// Use the API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the API in the jcrop_api variable
jcrop_api = this;
});

function updatePreview(c){
if (parseInt(c.w) > 0)
{
var rx = 48 / c.w; //小头像预览Div的大小
var ry = 48 / c.h;

$('#preview').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 rx = 199 / c.w; //大头像预览Div的大小
var ry = 199 / c.h;
$('#preview2').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'
});
}
};


function updateCoords(c)
{
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
};

},500);

}

这里稍作两点提醒:

其一:不要忘记在页面头部引入插件:

  <script src="/plug/js/jquery.min.js" type="text/javascript"></script>
  <script src="/plug/js/jquery.Jcrop.min.js" type="text/javascript"></script>
  <link rel="stylesheet" href="/plug/css/Jcrop.css" rel="external nofollow" type="text/css" />

其二:有些人眼尖的话可能看到了JS里有个定时,同时心理是不是很疑惑这不是有点多此一举吗?其实不是,上传图片到JS加载到页面上,是需要时间的,这个定时的意义在于

等到图片被JS加载到页面上时才去加载裁剪效果,这里也是反复实验后得出的做法。 

后端PHP处理我用的是THINKPHP框架,版本是3.1.3

贴上代码:

function crop_deal(){
  ob_clean();
  import ( 'ORG.Net.UploadFile' );
  $upload = new UploadFile ();
  $upload->maxSize = 2000000;
  $upload->allowExts = array (
    'jpg',
    'gif',
    'png',
    'jpeg'
  );
  $upload->savePath = './upload/test/';
  $upload->autoSub = true;
  $upload->subType = 'date';
  $upload->dateFormat = 'Ymd';
  if ($upload->upload () ) {
    $info = $upload->getUploadFileInfo();
    $new_path = "./upload/test/thumb".date('Ymd');
    $file_store = $new_path."/".date('YmdHis').".jpg";
    if(!file_exists($new_path)){
      mkdir($new_path,0777,true);
    }
    $source_path = "http://".$_SERVER['HTTP_HOST']."/upload/test/".$info[0]['savename'];
    $img_size = getimagesize($source_path);
    $width = $img_size[0];
    $height = $img_size[1];  
    $mime = $img_size['mime'];
    $srcImg = imagecreatefromstring(file_get_contents($source_path));
    $cropped_img = imagecreatetruecolor($_POST['w'], $_POST['h']);
    //缩放
    // imagecopyresampled($cropped_img,$srcImg,0,0,$_POST['x'],$_POST['y'],$_POST['w'],$_POST['h'],$width,$height);
    //裁剪
    imagecopy($cropped_img,$srcImg,0,0,$_POST['x'],$_POST['y'],$_POST['w'],$_POST['h']);
    header("Content-Type:image/jpeg");
    imagejpeg($cropped_img,$file_store);
    imagedestroy($srcImg);
    imagedestroy($cropped_img);
  }

}

这里就是调用GD库里创建图像的一系列方法,最重要就是imagecopy() ,它是将原图按规定的裁剪位置,裁剪大小复制到新的图片上去,这也说明了一件事,页面用户在裁剪图片

的时候其实前端并没有对图片操作,而是得到裁剪时的坐标位置,裁剪大小,然后提交到PHP操作!!

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者使用Swift能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

相关文章

最新评论