Let me show you the renderings first:
Page code
The user's uuid is written in dead test
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE><html lang="en"><head><title>User avatar cropping</title><meta http-equiv="Content-type" content="text/html;charset=UTF-8" /><link rel="stylesheet" href="resources/Jcrop/css/jquery.Jcrop.css"><link rel="stylesheet" href="resources/css/photo.css"><script src="resources/js/jquery.min.js"></script><script src="resources/Jcrop/js/jquery.Jcrop.js"></script><script src="resources/js/ajaxfileupload.js"></script><body><div><div><div><div><div><h1>Avatar cropping</h1></div><img src="resources/img/test.jpg" id="target" /><div id="preview-pane" ><div><img src="resources/img/test.jpg"/></div ><div style='float:left;display:inline;'><a class='btn_addPic' href="javascript:void(0);"><span><EM>+</EM>Add image</span> <input id="upload_image" type="file" name="upload" accept="image/*" class = "filePrew"/></a></div><div style='float:right;display:inline;'><a class='btn_addPic' href="javascript:void(0);" onclick='submit()'><span>Submit</span> </a></div></div></div></div></div></div></body><script type="text/javascript">var global_api = "";var boundx ="";//page image width var boundy ="";//page image height var tag = false;$(function() {// Create variables (in this scope) to hold the API and image size//create variables (in this scope) API and image size var jcrop_api,// Grab some information about the preview pane//get some information preview pane $preview = $('#preview-pane'),$pcnt = $('#preview-pane .preview-container'),$pimg = $('#preview-pane .preview-container img'),xsize = $pcnt.width(),ysize = $pcnt.height();$('#target').Jcrop({onChange: updatePreview,onSelect: updatePreview,aspectRatio: xsize / ysize},function(){// Use the API to get the real image size//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//Storage APIjcrop_api = this;// Move the preview into the jcrop container for css positioning//Preview Enter the jcrop container css positioning $preview.appendTo(jcrop_api.ui.holder);});function updatePreview(c){if (parseInt(cw) > 0)global_api=c;{var rx = xsize / cw;var ry = ysize / ch;$pimg.css({width: Math.round(rx * boundx) + 'px',height: Math.round(ry * boundy) + 'px',marginLeft: '-' + Math.round(rx * cx) + 'px',marginTop: '-' + Math.round(ry * cy) + 'px'});}};//===================$('#upload_image').change(function(event) {// Get the HTML5 js object of the file according to this <input> var files = event.target.files, file; if (files && files.length > 0) {// Get the currently uploaded file file = files[0];// The following is the key key, generate an available image URL through this file object// Get the URL of the window tool var URL = window.URL || window.webkitURL;// Generate the target urlvar imgURL = URL.createObjectURL(file);// Use this URL to generate a <img> to display it $('.jcrop-holder img').attr('src', imgURL);$('.preview-container img').attr('src', imgURL);}});//=============================================$("#upload_image").change(function(){tag=true;});});//============================================================================================================================================================================================================================================================================================================================================================================================================================= ""){ajaxFileUpload();}else{alert('Did you do nothing?');}}//ajax file upload function ajaxFileUpload() {$.ajaxFileUpload({url: 'uploadphoto', //The server-side request address used for file upload secureuri: false, //Generally set to falsefileElementId: 'upload_image', //The id attribute dataType: 'json', //The return value type is generally set to jsondata:{x:global_api.x,y:global_api.y,w:global_api.w,h:global_api.h,pw:boundx,ph:boundy,unid:'test'}, //The data uploaded together succeeds: function (data){ //The server successfully responds to the processing function if(data.result){alert('success');}else{alert('failed');}window.location.reload();//Refresh the current page}});}</script></html>Background code
@ResponseBody@RequestMapping("uploadphoto")public Map<String, Object> uploadPhoto(@RequestParam("upimage") MultipartFile imageFile, HttpServletRequest request,HttpServletResponse response) throws Exception {Map<String, Object> result = new HashMap<String, Object>();boolean tag =false;String unid = request.getParameter("unid");String x = request.getParameter("x");String y = request.getParameter("y");String h = request.getParameter("h");String w = request.getParameter("w");// The actual image width and height of the page String pheight = request.getParameter("ph");String pweight = request.getParameter("pw");// The graph cut parameter int imageX = Integer.parseInt(x);int imageY = Integer.parseInt(y);int imageH = Integer.parseInt(h);int imageW = Integer.parseInt(w);int srcH = Integer.parseInt(pheight);int srcW = Integer.parseInt(pweight);String realPath = request.getSession().getServletContext().getRealPath("/");String resourcePath = "resources/uploadImages/";try {if (imageFile != null) {if (FileUploadUtil.allowUpload(imageFile.getContentType())) {// The intercept operation starts here byte[] b = ImageCut.imgCut(imageFile.getInputStream(), imageX, imageY, imageW, imageH, srcW, srcH);if (b != null) {// Save to the database User user = userService.selectByPrimaryKey(unid);user.setPhoto(b);tag = (userService.updateByPrimaryKeySelective(user)==1)?tag=true:tag;result.put("result", tag);}}}} catch (Exception e) {e.printStackTrace();}result.put("result", tag);return result;}Image cutting tools
package com.ssm.demo.utils;import java.awt.Graphics;import java.awt.Image;image java.awt.Toolkit;import java.awt.image.BufferedImage;image java.awt.image.CropImageFilter;import java.awt.image.FilteredImageSource;import java.awt.image.ImageFilter;import java.io.ByteArrayOutputStream;import java.io.InputStream;import javax.imageio.ImageIO;public class ImageCut {/*** Image Intercept* * @param srcImageFile* Original image address* @param x* x coordinates during intercept* @param y* y coordinates during intercept* @param desWidth* Intercepted width* @param desHeight* Intercepted height* @param srcWidth* Page image Width* @param srcHeight* Page image height* */public static byte[] imgCut(InputStream input, int x, int y, int desWidth, int desHeight, int srcWidth, int srcHeight) {try {Image img;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);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();// Output file ByteArrayOutputStream out = new ByteArrayOutputStream();ImageIO.write(tag, "JPEG", out);return out.toByteArray();}} catch (Exception e) {e.printStackTrace();}return null;}}The above is the example code for uploading JCrop+ajaxUpload image cutting and uploading that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!