zoukankan      html  css  js  c++  java
  • 前端图像 裁剪利器 JQuerJjcrop+裁剪图像保存教程

    由于一个项目中需要用到用户头像上传裁剪组件,这两天便网上找了一些相关插件,主要由以下几种插件:

    1、Image Cropper:http://elemefe.github.io/image-cropper/#demo

    2、flash头像上传组件:http://www.hdfu.net/index.html(可惜是收费的)

    3、jQuery Jcrop:http://code.ciaoca.com/jquery/jcrop/

    本着开源免费的态度,第二种要收费的插件自然不纳入考虑学习的范围。

    本文主要是讲解jQuery Jcrop的基本用法以及和后端(这里采用java)相结合,保存裁剪后的图像。

    效果图如下:

    第一步:下载相关文件

      当然是去jQuery Jcrop官网下载jQuery Jcrop插件所需的css和js文件,下载过程这里就不详细介绍了。

    第二步 介绍jQuery Jcrop基本用法

      1、使用方法

      2、参数说明

      3、API接口 

    (一)使用方法

    1、引入css文件

    <link rel="stylesheet" href="resources/jcrop/css/jquery.Jcrop.min.css" type="text/css" />

    2、引入js文件

    <script src="resources/jcrop/js/jquery.min.js"></script>
    <script src="resources/jcrop/js/jquery.Jcrop.min.js"></script>

    3、给需要裁剪的图片加上id标签

    <img src="resources/fj.jpg" id="target" />

    这里给图片加上id=“target”

    4、调用Jcrop

    $('#target').Jcrop({
      //在这里添加所需要的参数
    });

    调用Jcrop的时候,可以在方法里面添加Jcrop所提供的各种参数、事件,比如可以添加onChange()事件

    (二)参数说明 

    名称默认值说明
    allowSelect true 允许新选框
    allowMove true 允许选框移动
    allowResize true 允许选框缩放
    trackDocument true 拖动选框时,允许超出图像以外的地方时继续拖动。
    baseClass 'jcrop' 基础样式名前缀。说明:class="jcrop-holder",更改的只是其中的 jcrop。

    例:假设值为 "test",那么样式名会更改为 "test-holder"

    addClass null 添加样式。

    例:假设值为 "test",那么会添加样式到class="jcrop-holder test"

    bgColor 'black' 背景颜色。颜色关键字、HEX、RGB 均可。
    bgOpacity 0.6 背景透明度
    bgFade false 使用背景过渡效果
    borderOpacity 0.4 选框边框透明度
    handleOpacity 0.5 缩放按钮透明度
    handleSize 9 缩放按钮大小
    aspectRatio 0 选框宽高比。说明:width/height
    keySupport true 支持键盘控制。按键列表:上下左右(移动选框)、Esc(取消选框)
    createHandles ['n','s','e','w','nw','ne','se','sw'] 设置边角控制器
    createDragbars ['n','s','e','w'] 设置边框控制器
    createBorders ['n','s','e','w'] 设置边框
    drawBorders true 绘制边框
    dragEdges true 允许拖动边框
    fixedSupport true 支持 fixed,例如:IE6、iOS4
    touchSupport null 支持触摸事件
    shade null 使用更好的遮罩
    boxWidth 0 画布宽度
    boxHeight 0 画布高度
    boundary 2 边界。说明:可以从边界开始拖动鼠标选择裁剪区域
    fadeTime 400 过度效果的时间
    animationDelay 20 动画延迟
    swingSpeed 3 过渡速度
    minSelect [0,0] 选框最小选择尺寸。说明:若选框小于该尺寸,则自动取消选择
    maxSize [0,0] 选框最大尺寸
    minSize [0,0] 选框最小尺寸
    onChange function(){} 选框改变时的事件
    onSelect function(){} 选框选定时的事件
    onDblClick function(){} 在选框内双击时的事件
    onRelease function(){} 取消选框时的事件

     (三)API接口

    名称说明
    setImage(string) 设定(或改变)图像。例:jcrop_api.setImage('newpic.jpg')
    setOptions(object) 设定(或改变)参数,格式与初始化设置参数一样
    setSelect(array) 创建选框,参数格式为:[x, y, x2, y2]
    animateTo(array) 用动画效果创建选框,参数格式为:[x, y, x2, y2]
    release() 取消选框
    disable() 禁用 Jcrop。说明:已有选框不会被清除。
    enable() 启用 Jcrop
    destroy() 移除 Jcrop
    tellSelect() 获取选框的值(实际尺寸)。例:console.log(jcrop_api.tellSelect())
    tellScaled() 获取选框的值(界面尺寸)。例:console.log(jcrop_api.tellScaled())
    getBounds() 获取图片实际尺寸,格式为:[w, h]
    getWidgetSize() 获取图片显示尺寸,格式为:[w, h]
    getScaleFactor() 获取图片缩放的比例,格式为:[w, h]

     第三步:前端页面中实际使用

    在我的页面中,我使用了实时预览裁剪图片的功能。如果需要更多功能,可以参照demo中的文件。

    首先贴上js代码部分

         
      $(function(){
        var
    jcrop_api, boundx, boundy, // Grab some information about the preview pane $preview = $('#preview-pane'), $pcnt = $('#preview-pane .preview-container'), $pimg = $('#preview-pane .preview-container img'), xsize = $pcnt.width(), ysize = $pcnt.height(); console.log('init', [ xsize, ysize ]); $('#target').Jcrop({ onChange : updatePreview, onSelect : updatePreview, aspectRatio : xsize / ysize //设为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; // Move the preview into the jcrop container for css positioning $preview.appendTo(jcrop_api.ui.holder); }); function updatePreview(c) { $('#x1').val(c.x); $('#y1').val(c.y); $('#x2').val(c.x2); $('#y2').val(c.y2); $('#w').val(c.w); $('#h').val(c.h); if (parseInt(c.w) > 0) { var rx = xsize / c.w; var ry = ysize / c.h; $pimg.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' }); } } });
      
    //这个函数是用来与后端交互,进行上传图片。上传图片成功后,返回图片的url
    function
    cut() { $.ajax({ type : "get", url : "JCropServlet?t=" + new Date(), data : { "x1" : $('#x1').val(), "x2" : $('#x2').val(), "y1" : $('#y1').val(), "y2" : $('#y2').val() }, dataType : "text", success : function(data) { $("#result").css("display", "block"); $("#result").attr("src", "resources/" + data); // location.reload(); }, error : function(data) { alert(data); } }); }
     

    接下来是jsp的代码

    <!-- 原图片 -->
        <img src="resources/fj.jpg" id="target" />
        <form id="coords" onSubmit="return false;" method="get" action="JCropServlet">
            <div class="inline-labels">
                <label>X1 <input type="text" size="4" id="x1" name="x1" /></label>
           <label>Y1 <input type="text" size="4" id="y1" name="y1" /></label>
    <label>X2<input type="text" size="4" id="x2" name="x2" /></label>
     <label>Y2 <input type="text" size="4" id="y2" name="y2" /></label>
    <label>W <input type="text" size="4" id="w" name="w" /></label>
    <label>H<input type="text" size="4" id="h" name="h" /> </label> </div> <button onclick="cut()">提交</button> </form>
      //这个div是用来实时预览实时裁剪的图像 <div id="preview-pane"> <div class="preview-container"> <img src="resources/fj.jpg" class="jcrop-preview" alt="Preview" /> </div> </div> <!-- 截图后的图片 --> <img src="" id="result" style="display: none">

    预览实时裁剪图像div的css代码

    #preview-pane{
      display: block;
      position: absolute;
      z-index: 2000;
      top: 10px;
      right: 30px;
      padding: 6px;
      border: 1px rgba(0,0,0,.4) solid;
      background-color: white;
      -webkit-border-radius: 6px;
      -moz-border-radius: 6px;
      border-radius: 6px;
      -webkit-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
      -moz-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
      box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
      }
      #preview-pane .preview-container {
      width: 250px;
      height: 250px;
      overflow: hidden;
      }

    第四步:后端接受图片,保存到本地。并通过返回图片url到前端页面。

    public class JCropServlet extends HttpServlet {
        public JCropServlet() {
            super();
        }
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
         //获取截取图片的坐标
    int x1=Integer.parseInt(request.getParameter("x1")); int y1=Integer.parseInt(request.getParameter("y1")); int x2=Integer.parseInt(request.getParameter("x2")); int y2=Integer.parseInt(request.getParameter("y2")); //获取根路径 String rootPath=request.getServletContext().getRealPath("/"); String src=rootPath+File.separator+"resources"+File.separator+"fj.jpg"; String name = "fj_crop_" + this.dateFormat() + ".jpg"; String dest=rootPath+File.separator+"resources"+File.separator+name; ImageUtils.delete(rootPath+File.separator+"resources"); ImageUtils.cut(src, dest, x1, y1, x2, y2); PrintWriter out=response.getWriter();
         //返回图片url out.print(name); out.close(); }
    private String dateFormat(){ DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); return df.format(new Date()); } }

    附上demo源码:

    http://pan.baidu.com/s/1gdvVMTX

  • 相关阅读:
    Git 基础
    SharePoint 2013 对象模型操作"网站设置"菜单
    SharePoint 2013 隐藏部分Ribbon菜单
    SharePoint 2013 Designer系列之数据视图筛选
    SharePoint 2013 Designer系列之数据视图
    SharePoint 2013 Designer系列之自定义列表表单
    SharePoint 2013 设置自定义布局页
    SharePoint 2013 "通知我"功能简介
    SharePoint 2013 创建web应用程序报错"This page can’t be displayed"
    SharePoint 禁用本地回环的两个方法
  • 原文地址:https://www.cnblogs.com/superman66/p/4652063.html
Copyright © 2011-2022 走看看