Crop pictures using the CROPPER plug-in

Clipper is a simple and powerful image clipping jQuery plug-in. The image clipping plug-in supports image zooming, image rotation, touch screen device, canvas and cross browser use.  
There are two ways for the clipper to upload the captured image data. One is that the front end sends the clipped data to the background for clipping and saving. The second is that the front end takes the clipped data and transfers it to base64 for uploading. The background uploads the image information through the binary stream. The second method is used here.

start

1, structure

Clipper.css clip plug-in (not changed)

Clipper.js clipping plug-in (unchanged)

index.html crop page

    jquery.min.js                

test.png test picture

ImgController.java receives base64 from the front end and saves the picture

2, code

The code is as follows, and the copy can be used directly.

html code:

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Insert title here</title>
	<link  href="cropper.css" rel="stylesheet">
	<style type="text/css">
		.container {
			width: 400px;
			height:400px;
		}
	</style>
</head>
<body>
	<div class="container">
		<img id="image" src="test.png">
	</div>
	<button type="button" onclick="uploadCropImg()">generate</button>
	
	<script src="jquery.min.js"></script>
	<script src="cropper.js"></script>
	<script type="text/javascript">
		$(document).ready(function (){
			$('.container > img').cropper({
				aspectRatio: 16 / 9,//Screenshot ratio
				crop: function(data) {
					// Come out the image data after cutting
				}
			});
		});
	
		/* Upload cropped image**/
	    function uploadCropImg(){
	        var $image = $("#image");
	        var src = $image.eq(0).attr("src");
	        var canvasdata = $image.cropper("getCanvasData");
	        var cropBoxData = $image.cropper('getCropBoxData');
	        convertToData(src, canvasdata, cropBoxData, function (imgBase64Str){
	            imgBase64Str = imgBase64Str.replace("data:image/jpeg;base64," , "");
	            imgBase64Str = imgBase64Str.replace("data:image/png;base64," , "");
	            $.ajax({
	                type: "post",
	                url: "/Project name/imgCon/uploadCropImg.do",
	                data: {
	                    imgBase64Str : imgBase64Str
	                },
	                success: function(data) {
	                    if(data == "success"){
	                        window.opener.cropImgSuccess();
	                    }else{
	                        alert("Upload failure");
	                    }
	                },error: function(request) {
	                    alert("Upload failure");
	                }
	            });
	        })
	    }
	     
	    /* Convert the cropped image to base64 string**/
	    function convertToData(url, canvasdata, cropdata, callback) {
	        var cropw = cropdata.width; // Width of shear
	        var croph = cropdata.height; // Width of shear
	        var imgw = canvasdata.width; // Height after picture zooming or zooming
	        var imgh = canvasdata.height; // Height after picture zooming or zooming
	         
	        var poleft = canvasdata.left - cropdata.left; // canvas locates the left side of the image
	        var potop = canvasdata.top - cropdata.top; // canvas locates the top of the picture
	         
	        var canvas = document.createElement("canvas");
	        var ctx = canvas.getContext('2d');
	         
	        canvas.width = cropw;
	        canvas.height = croph;
	         
	        var img = new Image();
	        img.src = url;
	         
	        img.onload = function() {
	            this.width = imgw;
	            this.height = imgh;
	                // This is mainly to understand the relationship between canvas and image clipping
	            ctx.drawImage(this, poleft, potop, this.width, this.height);
	            var base64 = canvas.toDataURL('image/jpg', 1);  // The "1" here refers to the sharpness (0-1) of the processed image. Of course, the smaller the image is, the more blurred it is, and the smaller the size of the processed image is
	            callback && callback(base64)      // Callback base64 string
	        }
	    } 
	</script>
</body>
</html>

java code:

package com.xwtec.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import sun.misc.BASE64Decoder;

@Controller
@Scope("prototype")
@RequestMapping("/imgCon")
public class ImgController {
	
	@RequestMapping(value = "/uploadCropImg.do", method=RequestMethod.POST)
    public void uploadCropImg(HttpServletRequest request, HttpServletResponse response ,
            @RequestParam(required=true) String imgBase64Str) throws IOException{
        boolean flag = generateImage(imgBase64Str, "d://hhh.png");
        if(flag){
            response.getWriter().write("success");         
        }else{
            response.getWriter().write("default");         
        }
    }
	
    public static boolean generateImage(String imgStr, String path) {
        if (imgStr == null)
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
	
}

After the project is started, click generate on the html page to save the image. Here I save it to the D disk directory.

End

Keywords: Java JQuery Javascript

Added by mrman23 on Wed, 01 Jan 2020 19:39:09 +0200