SpringMVC와 Jcrop을 결합하여 이미지 자르기

본고의 실례는 여러분에게 SpringMVC가 Jcrop과 결합하여 이미지 재단을 실현하는 구체적인 코드를 공유하여 참고하도록 하였으며, 구체적인 내용은 다음과 같다.
1. jsp 페이지:

<form name="form" action="<%=request.getContextPath()%>/UploadDemo/uploadHeadImage" class="form-horizontal" 
   method="post" enctype="multipart/form-data"> 
  <div class="modal-body text-center"> 
    <div class="zxx_main_con"> 
      <div class="zxx_test_list"> 
        <input class="photo-file" type="file" name="imgFile" id="fcupload" onchange="readURL(this);"/> 
        <img alt="" src="" id="cutimg"/> 
        <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"/> 
      </div> 
    </div> 
  </div> 
   
  <div class="modal-footer"> 
    <button id="submit" onclick=""> </button> 
  </div> 
</form> 
2. jcrop 구성 요소 참조 상황:

<link rel="stylesheet" href="<c:url value="/resources/uploadPlugin/css/jquery.Jcrop.css"/>" type="text/css"></link> 
  <script type="text/javascript" src="<c:url value="/resources/uploadPlugin/scripts/jquery-1.8.3.js"/>"></script> 
  <script type="text/javascript" src="<c:url value="/resources/uploadPlugin/scripts/jquery.Jcrop.js"/>"></script> 
3. jcrop 사용 방법

<script type="text/javascript"> 
   // api,  
    var api = null; 
    function readURL(input) { 
      if (input.files && input.files[0]) { 
        var reader = new FileReader(); 
        reader.readAsDataURL(input.files[0]); 
        reader.onload = function (e) { 
          $('#cutimg').removeAttr('src'); 
          $('#cutimg').attr('src', e.target.result); 
          api = $.Jcrop('#cutimg', { 
            setSelect: [ 20, 20, 200, 200 ], 
            aspectRatio: 1, 
            onSelect: updateCoords 
          }); 
        }; 
        if (api != undefined) { 
          api.destroy(); 
        } 
      } 
      function updateCoords(obj) { 
        $("#x").val(obj.x); 
        $("#y").val(obj.y); 
        $("#w").val(obj.w); 
        $("#h").val(obj.h); 
      }; 
    } 
  </script> 
넷째, 백그라운드 코드:

@RequestMapping(value = "/uploadHeadImage") 
  public String uploadHeadImage( 
      HttpServletRequest request, 
      @RequestParam(value = "x") String x, 
      @RequestParam(value = "y") String y, 
      @RequestParam(value = "h") String h, 
      @RequestParam(value = "w") String w, 
      @RequestParam(value = "imgFile") MultipartFile imageFile 
  ) throws Exception{ 
    System.out.println("==========Start============="); 
    String realPath = request.getSession().getServletContext().getRealPath("/"); 
    String resourcePath = "resources/uploadImages/"; 
    if(imageFile!=null){ 
      if(FileUploadUtil.allowUpload(imageFile.getContentType())){ 
        String fileName = FileUploadUtil.rename(imageFile.getOriginalFilename()); 
        int end = fileName.lastIndexOf("."); 
        String saveName = fileName.substring(0,end); 
        File dir = new File(realPath + resourcePath); 
        if(!dir.exists()){ 
          dir.mkdirs(); 
        } 
        File file = new File(dir,saveName+"_src.jpg"); 
        imageFile.transferTo(file); 
        String srcImagePath = realPath + resourcePath + saveName; 
        int imageX = Integer.parseInt(x); 
        int imageY = Integer.parseInt(y); 
        int imageH = Integer.parseInt(h); 
        int imageW = Integer.parseInt(w); 
        //  
        System.out.println("==========imageCutStart============="); 
        ImageCut.imgCut(srcImagePath,imageX,imageY,imageW,imageH); 
        System.out.println("==========imageCutEnd============="); 
      } 
    } 
    return "user/uploadImg/test"; 
  } 
5. ImageCut.java 도구 클래스:

/** 
   *   
   * @param srcImageFile   
   * @param x   x  
   * @param y   y  
   * @param desWidth    
   * @param desHeight    
   */ 
  public static void imgCut(String srcImageFile, int x, int y, int desWidth, 
               int desHeight) { 
    try { 
      Image img; 
      ImageFilter cropFilter; 
      BufferedImage bi = ImageIO.read(new File(srcImageFile+"_src.jpg")); 
      int srcWidth = bi.getWidth(); 
      int srcHeight = bi.getHeight(); 
      if (srcWidth >= desWidth && srcHeight >= desHeight) { 
        Image image = bi.getScaledInstance(srcWidth, srcHeight,Image.SCALE_DEFAULT); 
        cropFilter = new CropImageFilter(x, y, desWidth, desHeight); 
        img = Toolkit.getDefaultToolkit().createImage( 
            new FilteredImageSource(image.getSource(), cropFilter)); 
        BufferedImage tag = new BufferedImage(desWidth, desHeight, 
            BufferedImage.TYPE_INT_RGB); 
        Graphics g = tag.getGraphics(); 
        g.drawImage(img, 0, 0, null); 
        g.dispose(); 
        //  
        ImageIO.write(tag, "JPEG", new File(srcImageFile+"_cut.jpg")); 
      } 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
  } 
6. jcrop의 두 가지 사용 방식:
1、

jQuery('#cropbox').Jcrop({
         onChange: showCoords,
         onSelect: showCoords
      });
2、

var api = $.Jcrop('#cropbox',{
         onChange: showPreview,
         onSelect: showPreview,
         aspectRatio: 1
      });
이상은 본문의 전체 내용입니다. 여러분의 학습에 도움이 되고 저희를 많이 응원해 주십시오.

좋은 웹페이지 즐겨찾기