Maison > interface Web > js tutoriel > le corps du texte

使用Javascript裁剪图片并存储的简单示例代码

黄舟
Libérer: 2017-03-20 15:00:11
original
1437 Les gens l'ont consulté

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

前言

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

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

还是比较薄弱。

实现效果:

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

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

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

实现方法如下: 

以下是简单的页面设计:

<p style="float:left;"><img id="target"></p>
<p style="width:48px;height:48px;margin:10px;overflow:hidden; float:left;"><img style="float:left;" id="preview" ></p>
<p style="width:190px;height:195px;margin:10px;overflow:hidden; float:left;"><img style="float:left;" id="preview2" ></p>
<form action="{:U(&#39;/test/crop_deal&#39;)}" 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>
Copier après la connexion

下面是JS代码:

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

var jcrop_api, boundx, boundy;

setTimeout(function(){


$(&#39;#target&#39;).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; //小头像预览p的大小
var ry = 48 / c.h;

$(&#39;#preview&#39;).css({
width: Math.round(rx * boundx) + &#39;px&#39;,
height: Math.round(ry * boundy) + &#39;px&#39;,
marginLeft: &#39;-&#39; + Math.round(rx * c.x) + &#39;px&#39;,
marginTop: &#39;-&#39; + Math.round(ry * c.y) + &#39;px&#39;
});
}
{
var rx = 199 / c.w; //大头像预览p的大小
var ry = 199 / c.h;
$(&#39;#preview2&#39;).css({
width: Math.round(rx * boundx) + &#39;px&#39;,
height: Math.round(ry * boundy) + &#39;px&#39;,
marginLeft: &#39;-&#39; + Math.round(rx * c.x) + &#39;px&#39;,
marginTop: &#39;-&#39; + Math.round(ry * c.y) + &#39;px&#39;
});
}
};


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

},500);

}
Copier après la connexion

这里稍作两点提醒:

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

  <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" />
Copier après la connexion

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

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

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

贴上代码:

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

}
Copier après la connexion

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

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

总结

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!