This article shares a complete case of uploading images in JavaWeb for reference. The specific content is as follows
Implementation ideas
• Use jcrop plugin to clip the coordinates of the picture on your phone
• Pass the collected parameters to the background, use java graphic objects to draw images for cropping
◦Background processing flow:
1. Compress the uploaded pictures in proportion and upload them to the file server, and save the compressed pictures in a local temporary directory.
2. Echo the compressed image to the page, use jcrop for cropping, and clip the coordinates on the phone (x, y, width, height)
■@paramx Target slice start point coordinate X
■@param y The target slice starting point coordinate Y
■@param width Target slice width ■@param height Target slice height
3. Backstage processing of cropping and uploading
jsp page
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@ page contentType="text/html;charset=UTF-8" language="java" %><!doctype html><html><head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title>Upload user avatar</title> <link href="${pageContext.request.contextPath}/js/cutImg/css/master.css" rel="stylesheet" /> <link href="${pageContext.request.contextPath}/js/cutImg/css/upload.css" rel="stylesheet" /> <link href="${pageContext.request.contextPath}/js/cutImg/css/jquery.rollbar.css" rel="stylesheet" /> <link href="${pageContext.request.contextPath}/js/cutImg/css/jquery.Jcrop.css" rel="stylesheet" /></head><body><div> <form id="uploadImgFrom" enctype="multipart/form-data" method="post"> <div> <div> <div> <div> <div> <div id="pic2" > <div id="uploadFile"> <div style="margin-left: 75px;"> <a href="javascript:;" id="upText" style="color:red;">Upload avatar</a> </div> <p> Support jpg and png formats<br /> Picture less than 2M </p> </div> <!--Return to display pictures--> <img src="" name="photo" id="originalImg"/> </div> </div> <p id="up_reload" style="display: none;"> <a href="javascript:;" style="color: red">Re-upload</a> </p> <input type="hidden" name="picval" id="picval" /> <input type="hidden" name="origpicval" id="origpicval" value="" /> <input type="hidden" name="temporigpic" id="temporigpic" /> <input type="hidden" name="fileID" id="fileID" size="100" /> <input type="hidden" name="fileUrl" id="fileUrl" size="100" /> <input type="hidden" name="imgHeight" id="imgHeight" size="100" /> <input type="hidden" name="imgWidth" id="imgWidth" size="100" /> </div> <div> <img id="preview_1" src="${pageContext.request.contextPath}/images/4-3.jpg"/> </div> <p> 400 x 300 pixels</p> <%--<div> <img id="preview_2" src=${pageContext.request.contextPath}/images/4-3.jpg /> </div> <p> 80 x 80 pixels</p>--%> <p> Drag or zoom to generate a satisfactory avatar</p> </div> <%-- <div id="img_description"> <textarea </div>--%> <div> <font id="upalert"></font> </div> </div> </div> <input type="hidden" name="x" id="x" size="5" /> <input type="hidden" name="w" id="w" size="5" /> <input type="hidden" name="h" id="h" size="5" /> <input type="hidden" name="imgUrl" id="imgUrl"/> <input type="hidden" name="imgId" id="imgId"/> <div> <div id="saveImage"> <a href="javascript:;" style="color: red">Save avatar</a> </div> </div> </form></div></body><script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.form.js"></script><script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.validate.min.js"></script><script type="text/javascript" src="${pageContext.request.contextPath}/js/check.js"></script><script type="text/javascript" src="${pageContext.request.contextPath}/js/check.js"></script><script src="${pageContext.request.contextPath}/js/cutImg/js/jquery-1.7.1.min.js" type="text/javascript"></script><script src="${pageContext.request.contextPath}/js/cutImg/js/jquery.form.js" type="text/javascript"></script><script src="${pageContext.request.contextPath}/js/cutImg/js/jquery-custom-file-input.js" type="text/javascript"></script><script src="${pageContext.request.contextPath}/js/cutImg/js/jquery-custom-file-input.js" type="text/javascript"></script><script src="${pageContext.request.contextPath}/js/cutImg/js/jquery.Jcrop.js" type="text/javascript"></script><script src="${pageContext.request.contextPath}/js/cutImg/js/jquery.rollbar.min.js" type="text/javascript"></script><script src="${pageContext.request.contextPath}/js/cutImg/js/jquery.rollbar.min.js" type="text/javascript"></script><script src="${pageContext.request.contextPath}/js/cutImg/js/upload.ui.photos.js" type="text/javascript"></script><script type="text/javascript" src="${pageContext.request.contextPath}/js/dialog/dialog.js?lib=false"></script><script type="text/javascript"> photos.JcorpWidth = 400;//Crop selection box width photos.JcorpHeight = 300;//Crop selection box height// photos.Widths = ["200", "80"];// The image size "width" array, define the width of different pictures from large to small according to the number of pictures // photos.Heights = ["200", "80"];// The image size "high" array, define the height of different pictures from large to small according to the number of pictures photos.UpLoad_FileID = "uploadFile";//Upload component attribute ID photos.UpLoad_FileTextID = "upText";//Upload component button text ID photos.UpLoad_AlertID = "upalert";//Hint text ID photos.UpLoad_AlertClassName = "error";//The style of prompt text photos.Upload_FormID = "uploadImgFrom";//Upload component form ID photos.UpLoad_OriginFileID = "originalImg";//Base image ID photos.UpLoad_ReLoadID = "up_reload";//Reupload component ID photos.UpLoad_PicValueID = "picval";//Upload the bottom image content ID photos.UpLoad_PicFileID = "fileID";///Upload the picture id photos.UpLoad_PicFileUrl = "fileUrl";///Upload the picture url photos.UpLoad_PicImgHeight="imgHeight";//The uploaded base image high photos.UpLoad_PicImgWidth="imgWidth";//The uploaded base image wide photos.UpLoad_TempOriginValueID = "temporigpic";//The original image content ID when this page is re-uploaded photos.UpLoad_OriginValueID = "origpicval";//The original image content ID when other pages enter photos.Upload_RollbarID = "pic2";//Custom scrollbar ID photos.UpLoad_SaveID = "saveImage";//The image saving button ID photos.UpLoad_PreviewPreFix = "preview_";//The ID prefix name of multiple small pictures of different sizes, the ID format of multiple small pictures "prefix" + number (starting from 1), example: id="photos_preview1" ... photos.ParentFileImgID = "imgUrl";//Parent picture control ID photos.ParentFileValueID = "imgId";//Parent picture address control ID photos.XID = "x";//x photos.YID = "y";//y photos.WID = "w";//w photos.HID = "h";//h photos.UpText_Format = "Sorry, only jpg, png, and bmp formats are supported for the time being";//Image format verification text/* photos.UpText_Size = "Sorry, the image size cannot exceed 2M";*//Image size verification text/*photos.UpText_Error = "Image upload error";//Upload error text*/ photos.Url_Check = "/Enterprise/filescheck";//Address photos.Url_UpLoad = "/Enterprise/uploadphoto?up=original";//Upload image loading base image photos.Url_ReLoad = "";//Reload address photos.Url_Save = "/Enterprise/saveimg?up=save";//The address of the image is saved</script></html>Background Java code
Image upload tool
package com.shengya.service.utils;import com.shengya.service.ImgContants;import org.apache.commons.fileupload.disk.DiskFileItem;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.commons.CommonsMultipartFile;import sun.misc.BASE64Encoder;import javax.crypto.Mac;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import javax.imageio.ImageIO;import javax.imageio.ImageReadParam;import java.awt.*;import java.awt.geom.AffineTransform;import java.awt.image.AffineTransformOp;import java.awt.image.BufferedImage;import java.io.*;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;import java.util.ArrayList;/** * @author Darcy * Created by Administrator on 2016/6/17. */public class UploadUtils { // public final static String RADIOURL = "http://211.102.216.237:8011/fileServer/webapi/Attachments/bio?"; public final static String RADIOURL = "http://192.168.1.15:8088/fileServer/webapi/Attachments/bio?"; public final static String URL = ImgContants.IMG_UPLOAD + "/file/UpLoadImage?"; public final static String FILEURL = ImgContants.IMG_UPLOAD + "/file/UpLoadFile?"; public final static String VEDIOURL = ImgContants.FILE_UPLOAD + "/file/UpLoadFile?"; public final static String CROPURL = ImgContants.IMG_UPLOAD + "/file/CropImage?"; private static byte[] readAsByteArr(InputStream is) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { byte[] bytes = new byte[1024]; int length = 0; while ((length = is.read(bytes)) != -1) { baos.write(bytes, 0, length); } return baos.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { try { baos.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } /** * Upload image* * @param file */ public static String submitImage(File file) throws UnsupportedEncodingException { String fileName = URLEncoder.encode(file.getName(), "UTF-8"); long fileSize = file.length(); boolean isReSuffix = true; int height = 0; int width = 500; String mark = "t"; String mode = "W"; String url = sign(URL) + "&ChannelNo=muying_android" + "&FileName=" + fileName + "&FileSize=" + fileSize + "&IsReSuffix=" + isReSuffix + "&Height=" + height + "&Width=" + width + "&Mark=" + mark + "&Mode=" + mode; System.out.println("url:" + url); HttpURLConnection conn = null; OutputStream outStream = null; BufferedInputStream bin = null; try { bin = new BufferedInputStream(new FileInputStream(file)); conn = (HttpURLConnection) new URL(url) .openConnection(); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoOutput(true); // conn.setFixedLengthStreamingMode(file.length()); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", file.length() + ""); // conn.setRequestProperty("Range", "bytes="+""); // Set the character encoding of HttpURLConnection conn.setRequestProperty("Accept-Charset", "UTF-8"); outStream = conn.getOutputStream(); byte[] buf = new byte[1024]; int len = 0; int lenCount = 0; while ((len = bin.read(buf)) != -1) { outStream.write(buf, 0, len);//OK lenCount = lenCount + len; } outStream.flush(); int responseCode = conn.getResponseCode(); if (responseCode == 200) { InputStream inStream = conn.getInputStream(); byte[] data1 = readAsByteArr(inStream); String json = new String(data1); inStream.close(); return json; } else { InputStream inStream = conn.getInputStream(); byte[] data1 = readAsByteArr(inStream); String json = new String(data1); inStream.close(); return json; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (outStream != null) { outStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } /** * Upload image* * @param file */ public static String submitWebImage(MultipartFile file) throws UnsupportedEncodingException { String fileName = URLEncoder.encode(file.getOriginalFilename(), "UTF-8"); long fileSize = file.getSize(); boolean isReSuffix = true; int height = 0; int width = 500; String mark = "t"; String mode = "W"; String url = sign(URL) + "&ChannelNo=muying_android" + "&FileName=" + fileName + "&FileSize=" + fileSize + "&IsReSuffix=" + isReSuffix + "&Height=" + height + "&Width=" + width + "&Mark=" + mark + "&Mode=" + mode; System.out.println("url:" + url); HttpURLConnection conn = null; OutputStream outStream = null; BufferedInputStream bin = null; try { bin = new BufferedInputStream(file.getInputStream()); conn = (HttpURLConnection) new URL(url) .openConnection(); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoOutput(true); // conn.setFixedLengthStreamingMode(file.length()); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", file.getSize() + ""); // conn.setRequestProperty("Range", "bytes="+""); // Set the character encoding of HttpURLConnection conn.setRequestProperty("Accept-Charset", "UTF-8"); outStream = conn.getOutputStream(); byte[] buf = new byte[1024]; int len = 0; int lenCount = 0; while ((len = bin.read(buf)) != -1) { outStream.write(buf, 0, len);//OK lenCount = lenCount + len; } outStream.flush(); int responseCode = conn.getResponseCode(); if (responseCode == 200) { InputStream inStream = conn.getInputStream(); byte[] data1 = readAsByteArr(inStream); String json = new String(data1); inStream.close(); return json; } else { InputStream inStream = conn.getInputStream(); byte[] data1 = readAsByteArr(inStream); String json = new String(data1); inStream.close(); return json; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (outStream != null) { outStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } /** * Upload video* * @param file */ public static String submitRadio(MultipartFile file) throws Exception { String url = signRadio(RADIOURL); System.out.println("url:" + url); HttpURLConnection conn = null; OutputStream outStream = null; BufferedInputStream bin = null; try { bin = new BufferedInputStream(file.getInputStream()); conn = (HttpURLConnection) new URL(url) .openConnection(); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", file.getSize() + ""); conn.setRequestProperty("Accept-Charset", "UTF-8"); outStream = conn.getOutputStream(); byte[] buf = new byte[1024]; int len = 0; int lenCount = 0; while ((len = bin.read(buf)) != -1) { outStream.write(buf, 0, len);//OK lenCount = lenCount + len; } outStream.flush(); int responseCode = conn.getResponseCode(); if (responseCode == 200) { InputStream inStream = conn.getInputStream(); byte[] data1 = readAsByteArr(inStream); String json = new String(data1); inStream.close(); return json; } else { InputStream inStream = conn.getInputStream(); byte[] data1 = readAsByteArr(inStream); String json = new String(data1); inStream.close(); return json; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (outStream != null) { outStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } /** * Upload resume snapshot* * @param fileName * @param content * @return * @throws UnsupportedEncodingException */ public static String submitFile(String fileName, String content) throws UnsupportedEncodingException { //content = URLEncoder.encode(content, "UTF-8"); fileName = URLEncoder.encode(fileName, "UTF-8"); byte[] contentBytes = content.getBytes(); long fileSize = contentBytes.length; boolean isReSuffix = true; int height = 0; int width = 500; String mark = "t"; String mode = "W"; String url = sign(FILEURL) + "&ChannelNo=muying_android" + "&FileName=" + fileName + "&FileSize=" + fileSize + "&IsReSuffix=" + isReSuffix + "&Height=" + height + "&Width=" + width + "&Mark=" + mark + "&Mode=" + mode; System.out.println("url:" + url); HttpURLConnection conn = null; OutputStream outStream = null; BufferedInputStream bin = null; try { conn = (HttpURLConnection) new URL(url) .openConnection(); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoOutput(true); // conn.setFixedLengthStreamingMode(file.length()); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", content.length() + ""); // conn.setRequestProperty("Range", "bytes="+""); // Set the character encoding of HttpURLConnection conn.setRequestProperty("Accept-Charset", "UTF-8"); outStream = conn.getOutputStream(); outStream.write(contentBytes, 0, contentBytes.length);//OK outStream.flush(); int responseCode = conn.getResponseCode(); if (responseCode == 200) { InputStream inStream = conn.getInputStream(); byte[] data1 = readAsByteArr(inStream); String json = new String(data1); inStream.close(); return json; } else { InputStream inStream = conn.getInputStream(); byte[] data1 = readAsByteArr(inStream); String json = new String(data1); inStream.close(); return json; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (outStream != null) { outStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } /** * Upload attachment* * @return json string* @throws UnsupportedEncodingException */ public static String submitFile(MultipartFile file) throws UnsupportedEncodingException { String fileName = URLEncoder.encode(file.getOriginalFilename(), "UTF-8"); long fileSize = file.getSize(); boolean isReSuffix = true; int height = 0; int width = 500; String mark = "t"; String mode = "W"; String url = sign(FILEURL) + "&ChannelNo=muying_android" + "&FileName=" + fileName + "&FileSize=" + fileSize + "&IsReSuffix=" + isReSuffix + "&Height=" + height + "&Width=" + width + "&Mark=" + mark + "&Mode=" + mode; System.out.println("url:" + url); HttpURLConnection conn = null; OutputStream outStream = null; BufferedInputStream bin = null; try { bin = new BufferedInputStream(file.getInputStream()); conn = (HttpURLConnection) new URL(url) .openConnection(); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoOutput(true); // conn.setFixedLengthStreamingMode(file.length()); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", file.getSize() + ""); // conn.setRequestProperty("Range", "bytes="+""); // Set the character encoding of HttpURLConnection conn.setRequestProperty("Accept-Charset", "UTF-8"); outStream = conn.getOutputStream(); byte[] buf = new byte[1024]; int len = 0; int lenCount = 0; while ((len = bin.read(buf)) != -1) { outStream.write(buf, 0, len);//OK lenCount = lenCount + len; } int responseCode = conn.getResponseCode(); if (responseCode == 200) { InputStream inStream = conn.getInputStream(); byte[] data1 = readAsByteArr(inStream); String json = new String(data1); inStream.close(); return json; } else { InputStream inStream = conn.getInputStream(); byte[] data1 = readAsByteArr(inStream); String json = new String(data1); inStream.close(); return json; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (outStream != null) { outStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } private static String sign(String baseurl) throws UnsupportedEncodingException { long currency = System.currentTimeMillis(); long timeStamp = currency / 1000; String data = "ActionName=UpLoadImage" + "&SecretKey=4b19f08dbf0adb82ce9cc7c207ec1dc9" + "&TimeStamp=" + timeStamp; String signature = hmac_sha1("4b19f08dbf0adb82ce9cc7c207ec1dc9", URLEncoder.encode(data, "UTF-8")); signature = signature.replace("%3D", "%3d"); signature = signature.replace("%3A", "%3a"); signature = signature.replace("%2F", "%2f"); return baseurl + data + "&Signature=" + signature; } private static String signRadio(String url) throws Exception { long currencybttime = System.currentTimeMillis(); String data = "secretKey=f1b79c865c424be46183a2f0a49a0f15" + "&timeStamp=" + currency; System.out.println("url:" + url + data); System.out.println("url = " + URLEncoder.encode(url + data, "utf-8")); String signature = HmacSha1Util.getSignature(URLEncoder.encode(url + data, "utf-8"), "f1b79c865c424be46183a2f0a49a0f15"); return url + data + "&signature=" + signature; } private static String hmac_sha1(String key, String datas) { String reString = ""; try { datas = datas.replace("%3A", "%3a"); datas = datas.replace("%2F", "%2f"); datas = datas.replace("%3D", "%3d"); byte[] data = key.getBytes("UTF-8"); // Construct a key based on the given byte array, and the second parameter specifies the name of a key algorithm SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1"); // Generate a Mac object with the specified Mac algorithm Mac mac = Mac.getInstance("HmacSHA1"); // Initialize the Mac object with the given key mac.init(secretKey); byte[] text = datas.getBytes("UTF-8"); // Complete Mac operation byte[] text1 = mac.doFinal(text); reString = new BASE64Encoder().encodeBuffer(text1); reString = URLEncoder.encode(reString, "UTF-8"); reString = reString.replace("%0A", ""); reString = reString.replace("%0D", ""); } catch (Exception e) { e.printStackTrace(); } return reString; } /** * Upload cropped image* zxiao 2016/09/01 * * @param fileID */ public static String submittedCutedWebImage(MultipartFile file,String fileID,String x,String y,String w,String h) throws UnsupportedEncodingException { String FileId=fileID; String[] CropWidths=new String[]{"50"};//Crop width//List<String> list=new List<String>(); //List<String> list = new ArrayList<String>(5); ArrayList<String> listCropWidths = new ArrayList<String>(); listCropWidths.add("400");// String[] CropHeights=new String[]{"50"};// Crop height ArrayList<String> listCropHeights = new ArrayList<String>(); listCropHeights.add("300"); int CropX=Integer.parseInt(x);// Crop x coordinate int CropY=Integer.parseInt(y);// Crop y coordinates// String[] CropFixs=new String[]{"l"};//Crop image mark set ArrayList<String> listCropFixs = new ArrayList<String>(); listCropFixs.add("l"); String SourceSuffix="jpg";//Base map suffix String SourceFix="";//Base map logo/* boolean isReSuffix = true; int height = 1000; int width = 750; String mark = "t"; String mode = "W";*/ String url = sign(CROPURL) + "FileId=" + fileID + "&CropWidths=" + listCropWidths + "&CropHeights=" + listCropHeights + "&CropX=" + CropX + "&CropY=" + CropY + "&CropFixs=" + listCropFixs + "&SourceSuffix=" + SourceSuffix+ "&SourceFix=" + SourceFix; System.out.println("url:" + url); HttpURLConnection conn = null; OutputStream outStream = null; BufferedInputStream bin = null; try { bin = new BufferedInputStream(file.getInputStream()); conn = (HttpURLConnection) new URL(url) .openConnection(); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoOutput(true); // conn.setFixedLengthStreamingMode(file.length()); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", file.getSize() + ""); // conn.setRequestProperty("Range", "bytes="+""); // Set the character encoding of HttpURLConnection conn.setRequestProperty("Accept-Charset", "UTF-8"); outStream = conn.getOutputStream(); byte[] buf = new byte[1024]; int len = 0; int lenCount = 0; while ((len = bin.read(buf)) != -1) { outStream.write(buf, 0, len);//OK lenCount = lenCount + len; } int responseCode = conn.getResponseCode(); if (responseCode == 200) { InputStream inStream = conn.getInputStream(); byte[] data1 = readAsByteArr(inStream); String json = new String(data1); inStream.close(); return json; } else { InputStream inStream = conn.getInputStream(); byte[] data1 = readAsByteArr(inStream); String json = new String(data1); inStream.close(); return json; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (outStream != null) { outStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } /**The image needs to be saved locally after uploading and cropping*zxiao 2016/09/01 * @param , * @param x * @param y * @param w * @param h * @return * @throws IOException */ public static String submitCropImage(MultipartFile file,Integer x,Integer y,Integer w,Integer h) throws IOException { String folder=System.getProperty("java.io.tmpdir"); File tempDir =new File(folder); //If the folder does not exist, create if (!tempDir .exists() && !tempDir .isDir ()) {// System.out.println("//Not exists"); tempDir .mkdir(); } //Compressed temporary file String Srcpath=folder+"scaleTemp.jpg"; //Get the suffix of the file/*File uploadFile = new File(Srcpath); InputStream inputStream = file.getInputStream(); FileInputStream fs= (FileInputStream) inputStream; String srcImg = URLEncoder.encode(file.getOriginalFilename(), "UTF-8"); String suffix=srcImg.substring(srcImg.lastIndexOf(".")+1);*/ //Crop the image cutImgUtils o = new cutImgUtils(x,y,w,h); o.setSrcpath(Srcpath); o.setSubpath(folder+"uptemp.jpg"); File tempFile = o.cut("jpg"); String s = submitImage(tempFile); return s; } /** * Get the width of the uploaded image* zxiao 2016/09/09 * @param file * @return */ public static int getImgWidth(MultipartFile file) throws IOException { InputStream is = null; BufferedImage src = null; int ret = -1; try { is = file.getInputStream(); src = javax.imageio.ImageIO.read(is); ret = src.getWidth(null); // Get the source image width is.close(); } catch (Exception e) { e.printStackTrace(); } return ret; } /** * Get the uploaded image high* zxiao 2016/09/09 * @param file * @return */ public static int getImgHeight(MultipartFile file) { InputStream is = null; BufferedImage src = null; int ret = -1; try { is = file.getInputStream(); src = javax.imageio.ImageIO.read(is); ret = src.getHeight(null); // Get the source image height is.close(); } catch (Exception e) { e.printStackTrace(); } return ret; } /** * Scale image (scaling by height and width) * @param file file object* @param result Scale image address* @param height Scale height* @param width Scale width* @param bb Is it necessary to fill in when the scale is incorrect: true is a fill; false is not fill in; */ public static void scale(MultipartFile file, String result, int height, int width, boolean bb) { try { double ratio = 0.0; // Scaling/*CommonsMultipartFile cf= (CommonsMultipartFile)file; DiskFileItem fi = (DiskFileItem)cf.getFileItem(); File f = fi.getStoreLocation();*/// File f = new File(srcImageFile); InputStream inputStream = file.getInputStream(); BufferedImage bi = ImageIO.read(inputStream); Image item = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH); // Calculate the scale if ((bi.getHeight() > height) || (bi.getWidth() > width)) { if (bi.getHeight() > bi.getWidth()) { ratio = (new Integer(height)).doubleValue() / bi.getHeight(); } else { ratio = (new Integer(width)).doubleValue() / bi.getWidth(); } AffineTransformOp op = new AffineTransformOp(AffineTransform .getScaleInstance(ratio, ratio), null); item = op.filter(bi, null); } if (bb) {//Fill BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.setColor(Color.white); g.fillRect(0, 0, width, height); if (width == item.getWidth(null)) g.drawImage(itemp, 0, (height - item.getHeight(null)) / 2, item.getWidth(null), item.getHeight(null), Color.white, null); else g.drawImage(itemp, (width - item.getWidth(null)) / 2, 0, item.getWidth(null), item.getHeight(null), Color.white, null); g.dispose(); item = image; } ImageIO.write((BufferedImage) item, "jpg", new File(result)); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { try { /* File file = new File("E://bole//doc//Service interface document//Bole service interface description v1.0.docx"); System.out.println("file = " + file); String json = submitFile(file); System.out.println("json = " + json);*/ } catch (Exception e) { e.printStackTrace(); } }} Image Cropping Tools
package com.shengya.service.utils;import javax.imageio.ImageIO;import javax.imageio.ImageReadParam;import javax.imageio.ImageReader;import javax.imageio.stream.ImageInputStream;import java.awt.*;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.util.Iterator;/** * Created by Administrator on 2016/9/1. */public class cutImgUtils { // ===The source image path name such as: c:/1.jpg private String srcpath; // ===The clip image storage path name. For example: c:/2.jpg private String subpath; public void setSrcpath(String srcpath) { this.srcpath = srcpath; } public void setSubpath(String subpath) { this.subpath = subpath; } // ===Slice point x coordinate private int x; private int y; // ===Slift point width private int width; private int height; public cutImgUtils() { } public cutImgUtils(int x, int y, int width, int height) { if(x<0){ x=0; }else{ this.x = x; } if(y<0){ y=0; }else{ this.y = y; } this.width = width; this.height = height; } /** * * Crop the image and save the new image after cropping. */ public File cut() throws IOException { FileInputStream is = null; ImageInputStream iis = null; try { // Read image files is = new FileInputStream(srcpath); /** * * Returns Iterator containing all currently registered ImageReaders, which claim to be able to decode the specified format. Parameters: formatName - Contains the informal format name. * * (such as "jpeg" or "tiff"), etc. */ Iterator<ImageReader> it = ImageIO .getImageReadersByFormatName("jpg"); ImageReader reader = it.next(); // Get the image stream iis = ImageIO.createImageInputStream(is); /** * * <p> * iis: read the source. true: Search forward only* </p> * . Mark it as 'Search forward only'. * * This setting means that images included in the input source will be read only in order, which may allow the reader * * to avoid cached those input portions containing data associated with previously read images. */ reader.setInput(iis, true); /** * * <p> * Class that describes how to decode streams* <p> * . Used to specify how to convert an image or set of images from a stream in the context of a Java Image I/O * * framework when input. Plugin for a specific image format* * * An instance of ImageReadParam will be returned from its ImageReader implementation's getDefaultReadParam method. */ ImageReadParam param = reader.getDefaultReadParam(); /** * * Image crop area. Rectangle specifies an area in the coordinate space, which can be defined by the coordinate (x, y), width, and height of the upper left vertex of the Rectangle object **. */ Rectangle rect = new Rectangle(x, y, width, height); // Provide a BufferedImage to use it as the target for decoding pixel data. param.setSourceRegion(rect); /** * Use the provided ImageReadParam to read the object specified by indexing imageIndex and return * * as a complete BufferedImage. */ BufferedImage bi = reader.read(0, param); // Save new image ImageIO.write(bi, "jpg", new File(subpath)); File file = new File("subpath"); return file; } finally { if (is != null) is.close(); if (iis != null) iis.close(); } } public File cut(String suffix) throws IOException { FileInputStream is = null; ImageInputStream iis = null; try { // Read the image file is = new FileInputStream(srcpath);// is = inputStream; /** * Returns Iterator containing all currently registered ImageReaders * * claiming to be able to decode the specified format. Parameters: formatName - Contains the informal format name. * * (such as "jpeg" or "tiff"), etc. * Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpg"); */ String suffixName=null; if(suffix.equals("gif")){ suffixName="gif"; }else if(suffix.equals("png")){ suffixName="png"; } else{ suffixName="jpg"; } Iterator<ImageReader> it = ImageIO .getImageReadersByFormatName(suffixName); ImageReader reader = it.next(); // Get the image stream iis = ImageIO.createImageInputStream(is); /** * * <p> * iis: read the source. true: Search forward only* </p> * . Mark it as 'Search forward only'. * * This setting means that images included in the input source will be read only in order, which may allow the reader * * to avoid cached those input portions containing data associated with previously read images. */ reader.setInput(iis, true); /** * * <p> * Class that describes how to decode streams* <p> * . Used to specify how to convert an image or set of images from a stream in the context of a Java Image I/O * * framework when input. Plugin for a specific image format* * * An instance of ImageReadParam will be returned from its ImageReader implementation's getDefaultReadParam method. */ ImageReadParam param = reader.getDefaultReadParam(); /** * * 图片裁剪区域。 Rectangle 指定了坐标空间中的一个区域,通过Rectangle 对象* * 的左上顶点的坐标(x,y)、宽度和高度可以定义这个区域。 */ Rectangle rect = new Rectangle(x, y, width, height); // 提供一个BufferedImage,将其用作解码像素数据的目标。 param.setSourceRegion(rect); /** * * 使用所提供的ImageReadParam 读取通过索引imageIndex 指定的对象,并将* * 它作为一个完整的BufferedImage 返回。 */ BufferedImage bi = reader.read(0, param); // 保存新图片ImageIO.write(bi, "jpg", new File(subpath)); File file = new File(subpath); return file; } finally { if (is != null) is.close(); if (iis != null) iis.close(); } }}遇到的问题总结:
-裁剪图片发生偏移现象<br />解决办法:使用压缩后的图片等比例收集裁切坐标信息
-MultipartFile 和File之间相互转化
第一种方法:
MultipartFile file = xxx; CommonsMultipartFile cf= (CommonsMultipartFile)file; DiskFileItem fi = (DiskFileItem)cf.getFileItem(); File f = fi.getStoreLocation();
会在项目的根目录的临时文件夹下生成一个文件;
The second method:
transferTo(File dest);
会在项目中生成一个新文件;
第三种方法:
File f = (File) xxx 强转即可。前提是要配置multipartResolver,要不然会报类型转换失败的异常。
<bean id="multipartResolver"> <property name="maxUploadSize" value="104857600"/> <property name="maxInMemorySize" value="4096"/> </bean>
没试过;
第四种方法:
Workbook wb = Workbook.getWorkbook(xxx .getInputStream());
转换为输入流,直接读取;
第五种方法:
byte[] buffer = myfile.getBytes();
先转换为字节数组,没试过;
第六种方法:
直接转成输入流
MultipartFile file=xxx; is = file.getInputStream(); src = javax.imageio.ImageIO.read(is); ret = src.getWidth(null); // 得到源图宽
References:
jcop api:http://code.ciaoca.com/jquery/jcrop/.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。