欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

js图片裁剪原理(手机*裁剪任意形状)

程序员文章站 2023-11-12 22:57:28
项目需求有个功能要实现头像,让我这个后端开发来做这个确实有点为难,结合网上大神的例子,做了个简单的功能,以备不时之需实现效果页面+js<%@ page language="java" impor...

项目需求有个功能要实现头像,让我这个后端开发来做这个确实有点为难,结合网上大神的例子,做了个简单的功能,以备不时之需

实现效果

js图片裁剪原理(手机*裁剪任意形状)

页面+js

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<%
string path = request.getcontextpath();
string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/";
response.setheader("pragma","no-cache");
response.setheader("cache-control","no-cache");
%>

<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
  <head>
    <base href="<%=basepath%>">
    
    <title>my jsp 'face.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
<%--    <link rel="stylesheet" href="<%=basepath%>static/css/bootstrap.css"/> --%>
    <link rel="stylesheet" href="<%=basepath%>static/css/common.css"/>
    <link rel="stylesheet" href="<%=basepath%>static/css/jquery.jcrop.css"/>
    <script type="text/javascript" src="<%=basepath%>static/js/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="<%=basepath%>static/js/ajaxfileupload.js"></script>
    <script type="text/javascript" src="<%=basepath%>static/js/bootstrap.js"></script>
    <script type="text/javascript" src="<%=basepath%>static/js/jquery.json-2.4.js" charset="utf-8"></script> 
    <script type="text/javascript" src="<%=basepath%>static/js/jquery.validate.js"></script> 
    <script type="text/javascript" src="<%=basepath%>static/js/jquery.jcrop.js"></script>
     
    <script type="text/javascript">
        /* jcrop对象,全局变量方便操作 */
        var api = null;
        /* 原图宽度 */
        var boundx;
        /* 原图高度 */
        var boundy;
        
        /* 选择图片事件 */
        function readurl(url){
            var reader = new filereader();
            reader.readasdataurl(url.files[0]);
            reader.onload = function(e){
                $("#faceid").removeattr("src");
                $("#lookid").removeattr("src");
                $("#faceid").attr("src",e.target.result);
                $("#lookid").attr("src",e.target.result); 
                $("#faceid").jcrop({
                    onchange: showpreview,
                    onselect: showpreview,
                    aspectratio: 1,
                    boxwidth:600
                  },function(){
                    // use the api to get the real image size
                    //使用api来获得真实的图像大小
                    var bounds = this.getbounds();
                    boundx = bounds[0];
                    boundy = bounds[1];
                    // store the api in the jcrop_api variable
                    //jcrop_api变量中存储api
                    api = this;
                    
                    $("#boundx").val(boundx);
                    $("#boundy").val(boundy);
                    
                  });
             };
              /* 移除jcrop */
              if (api != undefined) {
                  api.destroy();
              }
              
            //简单的事件处理程序,响应自onchange,onselect事件,按照上面的jcrop调用
            function showpreview(coords){
                /* 设置剪切参数 */
                $("#x").val(coords.x);
                $("#y").val(coords.y);
                $("#w").val(coords.w);
                $("#h").val(coords.h);
                if(parseint(coords.w) > 0){
                    //计算预览区域图片缩放的比例,通过计算显示区域的宽度(与高度)与剪裁的宽度(与高度)之比得到
                    var rx = $("#preview_box").width() / coords.w; 
                    var ry = $("#preview_box").height() / coords.h;
                    $("#lookid").css({
                        width:math.round(rx * $("#faceid").width()) + "px", //预览图片宽度为计算比例值与原图片宽度的乘积
                        height:math.round(rx * $("#faceid").height()) + "px",   //预览图片高度为计算比例值与原图片高度的乘积
                        marginleft:"-" + math.round(rx * coords.x) + "px",
                        margintop:"-" + math.round(ry * coords.y) + "px"
                    });
                }
            }

        }
    
    
    </script>
    

  </head>
  
  <body>
    <form name="form" action="<%=basepath%>faceupload.do" class="form-horizontal" method="post" enctype="multipart/form-data">
        <dir></dir>
        <div style="margin-top: 10;margin-left: 30%">
            <table>
                <tr>
                    <td>
                        <span>头像:</span>
                        <input class="photo-file" type="file" name="imgfile" id="imgfile" onchange="readurl(this) " />
                    </td>
                    <td>
                            <!--  -->
                            <img id = "faceid" src="<%=basepath%>static/img/1.jpg" class="jcrop-preview" alt="附件">


                        <!-- 图片长宽高隐藏域 -->
                        <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="hidden" id="boundx" name="boundx" >
                        <input type="hidden" id="boundy" name="boundy" >

                    </td>
                </tr>
                
                <tr>
                    <td>
                        <span>头像预览:</span>
                    </td>
                    <td >
                        <div style="width: 200px;height: 200px;overflow: hidden;" id = "preview_box">
                        <img id = "lookid" src="<%=basepath%>static/img/1.jpg" class="jcrop-preview" alt="预览" >
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <span>用户名:</span><input type="text" id ="username" name ="username">
                    </td>
                    <td >
                        <span>艺名:</span><input type="text" id ="artname" name ="artname" >
                    </td>
                </tr>
                
            </table>
            
             <div class="modal-footer">
                 <button id="submit" onclick="">上传</button>
            </div>
        </div>
    </form>
  </body>
</html>

后端控制器

package com.lovo.controller;

import java.io.file;
import java.text.simpledateformat;
import java.util.date;

import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

import org.apache.log4j.logger;
import org.springframework.stereotype.controller;
import org.springframework.ui.model;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.multipart.multipartfile;

import com.lovo.utils.cutimgeutil;
import com.lovo.utils.fileuploadcheck;


@controller
public class facecontroller {
    
    private static logger logger = logger.getlogger(facecontroller.class);

    @requestmapping(value = "/faceupload.do",method = requestmethod.post)
    public void facelogincontroller(httpservletrequest request,httpservletresponse response,model model,
            @requestparam("imgfile") multipartfile imgfile,string username,string artname){
        
        //剪裁图片坐标
        string x = request.getparameter("x");
        string y = request.getparameter("y");
        string w = request.getparameter("w");
        string h = request.getparameter("h");
        
        //原始图片坐标
        string boundx = request.getparameter("boundx");
        string boundy = request.getparameter("boundy");
        
        //切图参数
        int imgex = (int) double.parsedouble(x);
        int imgey = (int) double.parsedouble(y);
        int imegw = (int) double.parsedouble(w);
        int imgeh = (int) double.parsedouble(h);
        int srcx = (int) double.parsedouble(boundx);
        int srcy = (int) double.parsedouble(boundy);
        
        //文件保存文件夹
        string path = request.getsession().getservletcontext().getrealpath("/")+"fileupload"+file.separator;
        //文件重命名
        date day = new date();
        simpledateformat sdf = new simpledateformat("yyyymmdd");
        string newname = sdf.format(day)+system.currenttimemillis()+".jpg";

        try 
        {
            //处理头像附件
            if(imgfile !=null)
            {
                //判断是否为图片文件
                if(fileuploadcheck.allowupload(imgfile.getcontenttype()))
                {
                    boolean cut = cutimgeutil.cutimge(imgfile.getinputstream(), imgex, imgey, imegw, imgeh, srcx, srcy, path+newname);
                    if(cut)
                    {
                        //当头像剪切成功进行用户信息数据库存储
                        system.out.println(username+" "+artname+" "+newname);
                    }
                    
                }
            }
            
        } catch (exception e)
        {
            e.printstacktrace();
            logger.error("上传失败");
        }
        
        
    }
}

工具类

package com.lovo.utils;

import java.awt.graphics;
import java.awt.image;
import java.awt.toolkit;
import java.awt.image.bufferedimage;
import java.awt.image.cropimagefilter;
import java.awt.image.filteredimagesource;
import java.awt.image.imagefilter;
import java.io.bytearrayoutputstream;
import java.io.file;
import java.io.inputstream;

import javax.imageio.imageio;

import org.apache.log4j.logger;



public class cutimgeutil {
    
    private static logger logger = logger.getlogger(cutimgeutil.class);
    
    /**
     * 图片剪切工具类
     * @param input 图片输入流
     * @param x 截取时的x坐标
     * @param y 截取时的y坐标
     * @param deswidth 截取的宽度
     * @param desheight 截取的高度
     * @param srcwidth 页面图片的宽度
     * @param srcheight 页面图片的高度
     * @param newfilepath 保存路径+文件名
     * @return
     */
    public static boolean cutimge(inputstream input, int x, int y, int deswidth, int desheight, int srcwidth,int srcheight,string newfilepath){
            
        boolean cutflag = true;
        
        try 
        {
            //图片类
            image imge ;
            imagefilter cropfilter;
            
            //读取图片
            bufferedimage bi = imageio.read(input);
            
            //当剪裁大小小于原始图片大小才执行
            if(srcwidth >= deswidth && srcheight >= desheight)
            {
                //获取原始图
                image image = bi.getscaledinstance(srcwidth, srcheight, image.scale_default);
                //获取新图
                cropfilter = new cropimagefilter(x, y, deswidth, desheight);
                imge = toolkit.getdefaulttoolkit().createimage(new filteredimagesource(image.getsource(), cropfilter));
                bufferedimage tag = new bufferedimage(deswidth, desheight, bufferedimage.type_int_rgb);
                graphics g = tag.getgraphics();
                g.drawimage(imge, 0, 0, null);
                g.dispose();
                
                file out = new file(newfilepath);
               // 输出文件
                imageio.write(tag, "jpeg", out);
            }
            
        } catch (exception e) 
        {
            cutflag = false;
            e.printstacktrace();
            logger.error("剪切失败");
        }
        return cutflag;
        
    }
}
package com.lovo.utils;

import java.util.arrays;
import java.util.list;

public class fileuploadcheck {
    
    //支持的文件类型
    public static final list<string> allow_types = arrays.aslist("image/jpg","image/jpeg","image/png","image/gif");

    //校验文件类型是否是被允许的
    public static boolean allowupload(string postfix){
        return allow_types.contains(postfix);
    }
}