手機自由裁剪任意形狀:js圖片裁剪原理

項目需求有個功能要實現頭像,讓我這個後端開發來做這個確實有點為難,結合網上大神的例子,做了個簡單的功能,以備不時之需

實現效果

JAVA spring+jcrop.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);
    }
}

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/223984.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-09 14:35
下一篇 2024-12-09 14:35

相關推薦

發表回復

登錄後才能評論