Javaweb to implement the full code of cropping picture upload _java

Source: Internet
Author: User

The example of this article for everyone to share the javaweb to achieve a complete cut picture upload case for your reference, the specific content as follows

Realize the idea

• Use the Jcrop plugin phone to crop the coordinates of the picture
• Pass the collected parameters to the background, and crop the images with Java drawing objects in the background
◦ Background processing process:
1, upload the picture in accordance with the proportion of compression after uploading to the file server, and the compressed image saved in the local temporary directory.
2, will compress the picture back to the page, uses Jcrop to cut, the handset cutting coordinates (x,y,width,height)
@paramx Target Slice start coordinates x
@param y target slice start coordinates y
Width of target slice @param width
Height of @param height target slice
3, the background processing crop clipping, upload again

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 class=" User_upload "> <form id=" Uploadimgfrom "enctype=" Multipart/form-data "method=" POST "> <div class=" Upload "> <div class=" Upload_ Left "> <div class=" pic "> <div class=" pic2 "id=" Pic2"> <div id=" uploadfile "> <div class=" upload_btn "style=" margin-left:75px; > <a href= "javascript:;" id= "Uptext" style= "color:red;"
                > Upload Avatar </a> </div> <p> support jpg, png format <br/> Pictures less than 2M </p> </div> <!--back to show pictures--> <img src= "" Nam E= "Photo" id= "originalimg" alt= ""/> </div> </div> <p class= "up_reload" id= "Up_ Reload "style=" Display:none; " > <a href= "javascript:;" style= "color:red" > re-upload </a> </p> <input type= "h
        Idden "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="/> <input type= "hidden" name= "FileUrl" id= "FileUrl" size= "M"/> "<input" type= "hidden" name= "ImgHeight" id= "ImgHeight" siz E= "/>" <input type= "hidden" name= "ImgWidth" id= "imgwidth" size= "/>" </div> ;d IV class= "Upload_right" > <div class= "upload_view_pic" style=; height:230px; Border:solid 1px #ccc; Overflow:hidden; "
        > <img id= "preview_1" src= "${pagecontext.request.contextpath}/images/4-3.jpg"/> </div> <p> x 300 pixels </p> <%--<div class= "Upload_view_pic" style= "width:80px ; height:80px; Border:solid 1px #ccc; Overflow:hidden; "
        > <img id= "preview_2" src=${pagecontext.request.contextpath}/images/4-3.jpg/> </div> <p> x 80 pixel </p>--%> <p> drag or zoom to generate your own satisfied avatar </p&gt
      ; </div> <%--<div id= "img_description"> <textarea </div>--%> <div class=" upload_b "> <font id=" Upalert ">& lt;/font> </div> </div> <input type= "hidden" name= "x" id= "x" size= "5"/> <input Type= "hidden" name= "y" id= "y" size= "5"/> <input "type=" hidden "W" name= "W" id= "5" size=/> Type = "hidden" name= "H" id= "H" size= "5"/> <input type= "hidden" name= "Imgurl" id= "Imgurl"/> <input type= "Hi Dden "Name=" Imgid "id=" Imgid "/> <div class=" Upload_submit_contain "> <div class=" upload_submit "id=" s
  Aveimage "> <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 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. 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/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;//cropping box select height//photos. widths = ["200", "80"];//picture size "wide" array, according to the picture number of sheets from large to small to define the width//photos of different pictures. Heights = ["200", "80"];//picture size "High" array, according to the picture number of sheets from large to small to define the height of different 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";//Prompt text to increase the style photos. Upload_formid = "Uploadimgfrom";//upload component form ID photos. Upload_originfileid = "originalimg";//Bottom chart picture ID photos. Upload_reloadid = "up_reload";//re-upload component ID photos. Upload_picvalueid = "Picval";//upload the bottom picture content ID photos. Upload_picfileid = "Fileid";////upload picture ID photos. Upload_picfileurl = "FileUrl";////upload image URL photos. Upload_picimgheight= "imgheight";//upload the bottom of the map high photos. Upload_picimgwidth= "ImgWidth";//upload the bottom of the map wide photos. Upload_temporiginvalueid = "Temporigpic";//the original picture content ID photos When this page is uploaded again. Upload_originvalueid = "Origpicval";//the original picture content ID photos when other pages enter. Upload_rollBarid = "Pic2";//custom scroll bar ID photos. Upload_saveid = "SaveImage";//Picture save button ID photos. Upload_previewprefix = "Preview_";//number of different size small map ID prefix name, multiple small map id format "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 support JPG, PNG, BMP format";//Picture format verification text/* photos. Uptext_size = "Sorry, the picture size cannot exceed 2M"; *///picture size verify text/*photos. Uptext_error = "error on the picture";//upload the wrong text/photos. Url_check = "/enterprise/filescheck";//file authentication size address photos. Url_upload = "/enterprise/uploadphoto?up=original";//upload image to load the address photos of the bottom map. Url_reload = "";//re-uploaded address photos.

 Url_save = "/enterprise/saveimg?up=save";//Save picture's address </script> </html>

Background Java code

Picture Upload Tool Class

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 the Administrator on 2016/6/17. */public class Uploadutils {//public final static String Radiourl = "Http://211.102.216.237:8011/fileServer/webapi/At
  Tachments/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 Picture * * @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= "+ He
    ight + "&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 HttpURLConnection character encoding 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 = =) {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 Picture * * @param file/public static String submitwebimage (Multipartfile file) throws Unsupporte
    dencodingexception {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= "+ He Ight + "&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 HttpURLConnection character encoding 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 = =) {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 {//conte
    NT = 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 HttpURLConnection character encoding Conn.setrequestproperty ("Accept-charset", "UTF-8");
      OutStream = Conn.getoutputstream ();
      Outstream.write (contentbytes, 0, contentbytes.length);//ok Outstream.flush ();
      int responsecode = Conn.getresponsecode ();
        if (Responsecode = =) {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 sub Mitfile (multipartfile file) throws Unsupportedencodingexception {String fileName = Urlencoder.encode (file.getoriginal
    Filename (), "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 HttpURLConnection character encoding 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 = =) {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 currebttime = System.curre
    Nttimemillis ();
    Long timeStamp = currebttime/1000; String data = "Actionname=uploadimage" + "&SECRETKEY=4B19F08DBF0ADB82CE9CC7C207EC1DC9" + "&timestamp=" + t
    Imestamp; 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 currebttime = System.currenttimemillis ();
    String data = "Secretkey=f1b79c865c424be46183a2f0a49a0f15" + "&timestamp=" + currebttime;
    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");
      Constructs a key based on a given byte array, and the second parameter specifies the name of a key algorithm secretkey Secretkey = new Secretkeyspec (data, "HmacSHA1");
      Generates a Mac object that specifies the Mac algorithm mac = mac.getinstance ("HmacSHA1");
      Initializes a Mac object Mac.init (Secretkey) with a given key;
      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 picture * Zxiao 2016/09/01 * * @param fileid/public static String Submitcutedwebimage (Multip Artfile file,string fileid,string x,string y,string w,string h) throws Unsupportedencodingexception {String FileId=fi
    Leid; String[] cropwidths=new string[]{"50"};Cutting 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-coordinate//string[] cropfixs=new string[]{"L"}
    //Crop The marked set of the picture arraylist<string> Listcropfixs = new arraylist<string> ();


    Listcropfixs.add ("L");
    string sourcesuffix= "JPG";//Bottom graph suffix String sourcefix= "";//Bottom Chart Indicator/* Boolean isresuffix = true;
    int height = 1000;
    int width = 750;
    String mark = "T"; string mode = "W"; */String URL = sign (cropurl) + "fileid=" + Fileid + "&cropwidths=" + li Stcropwidths + "&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 HttpURLConnection character encoding 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 = =) {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 after cropping the picture needs to save a copy locally *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 an if (!tempdir. Exists () &&!tempdir. Isdirectory ()) {//System.out.println ("//Non-existent");
    TempDir. mkdir ();

    }//Compressed temporary file String srcpath=folder+ "Scaletemp.jpg";
    Gets 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 picture 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 upload picture's wide * Zxiao 2016/09/09 * @param file * @return/public static int Getimgwidth (Multipar
    Tfile 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 map wide is.close ();
    catch (Exception e) {e.printstacktrace ();
  return ret; /** * Get upload image high * zxiao 2016/09/09 * @param file * @return/public static int Getimgheight (Multipar
    Tfile 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 Figure high is.close ();
    catch (Exception e) {e.printstacktrace ();
  return ret; /** * Zoom image (zoom by height and width) * @param file Object * @Param result scaled image address * @param height after height * @param width zoom * @param BB ratio is not correct when required filler: true for filler;
   False is not filler; */public static void scale (Multipartfile file, String result, int height, int width, boolean bb) {try {Doub Le 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 itemp = bi.getscaledinstance (width, height, bi.)
      Scale_smooth); Calculate scale if (bi.getheight () > height) | | (Bi.getwidth () > width)) {if (Bi.getheight () > Bi.getwidth ()) {ratio = (new Integer (height)). Doublevalue ()/b
        I.getheight ();
        else {ratio = (new Integer (width)). Doublevalue ()/bi.getwidth (); } affinetransformop op = new Affinetransformop (affinetransform. Getscaleinstance (ratio, ratio), null);
      itemp = op.filter (bi, NULL); } if (BB) {//filler bufferedimage image = new BufferedImage (width, height, bufferedimage.type_int_rg
        B);
        Graphics2D g = image.creategraphics ();
        G.setcolor (Color.White);
        G.fillrect (0, 0, width, height); if (width = = itemp.getwidth (null)) G.drawimage (itemp, 0, (Height-itemp.getheight (NULL))/2, ITE
        Mp.getwidth (NULL), itemp.getheight (null), color.white, NULL); else G.drawimage (itemp, (Width-itemp.getwidth (NULL))/2, 0, itemp.getwidth (null), Itemp.getheig
        HT (NULL), color.white, NULL);
        G.dispose ();
      itemp = image;
    } imageio.write ((bufferedimage) itemp, "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 ();

 }
  }
}

Picture cropping tool class

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 the Administrator on 2016/9/1.

  */public class Cutimgutils {//= = Source Picture path name: c:\1.jpg private String Srcpath; = = = Cut the picture to store the path name.
  such as: C:\2.jpg private String subpath;
  public void Setsrcpath (String srcpath) {this.srcpath = Srcpath;
  } public void Setsubpath (String subpath) {this.subpath = subpath;

  }//= = Cut point x coordinates private int x;

  private int y;
  = = = Cut 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;
   /** * * Cut the picture and save the new picture of the crop.
    * * Public File Cut () throws IOException {FileInputStream is = null;
    Imageinputstream IIS = NULL;

      try {//Read picture file is = new FileInputStream (Srcpath); /** * Returns the iterator containing all currently registered ImageReader, which claim to be able to decode the specified format.
       Parameters: FormatName-contains informal format names.
       * * (for example, "JPEG" or "TIFF").

      * * iterator<imagereader> it = ImageIO. Getimagereadersbyformatname ("JPG");

      ImageReader reader = It.next ();

      Get Picture Stream IIS = Imageio.createimageinputstream (IS); /** * * <p> * IIS: Read source.
       True: Search forward only * </p> *. mark it as ' forward only '.
       * * This setting means that the images contained in the input source will be read in sequential order and may allow reader * * To avoid caching those input parts that contain data associated with previously read images.

      */Reader.setinput (IIS, True); /** * * <p> * Describes how to decode the convection class * <p>
       *. Used to specify how the flow from the context of the Java Image I/O * frame is exchanged for an image or set of images at input time.
       The plug-in for a particular image format * * will return an instance of * * Imagereadparam from its ImageReader implemented Getdefaultreadparam method.

      * * Imagereadparam param = Reader.getdefaultreadparam (); /** * * Picture cropped area.
       Rectangle specifies an area in the coordinate space that can be defined by the coordinates (X,Y), width, and height of the upper-left vertex of the Rectangle object *.

      * * Rectangle rect = new Rectangle (x, y, width, height);
      Provides a bufferedimage that is used as a target for decoding pixel data.

      Param.setsourceregion (rect);
       /** * uses the provided imagereadparam to read the object specified by the index imageindex and returns * * it as a complete bufferedimage.

      * * BufferedImage bi = reader.read (0, param);
      Save the new picture Imageio.write (bi, "jpg," "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 picture file is = new FileInputStream (srcpath);//is = InputStream; /** * Returns the iterator containing all currently registered ImageReader, which claim to be able to decode the specified format.
       Parameters: FormatName-contains informal format names.
       * * (for example, "JPEG" or "TIFF").
       * 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 Picture Stream IIS = Imageio.createimageinputstream (IS); /** * * <p> * IIS: Read source.
       True: Search forward only * </p> *. mark it as ' forward only '. * * This setting means that the images contained in the input source will be read in order only and may allow readER * * Avoids caching of those input parts that contain data associated with previously read images.

      */Reader.setinput (IIS, True);
       /** * * <p> * Describes how to decode the convection class * <p> *. Used to specify how to input from Java Image I/o * * A flow in the context of a frame to exchange an image or a set of images.
       The plug-in for a particular image format * * will return an instance of * * Imagereadparam from its ImageReader implemented Getdefaultreadparam method.

      * * Imagereadparam param = Reader.getdefaultreadparam (); /** * * Picture cropped area.
       Rectangle specifies an area in the coordinate space that can be defined by the coordinates (X,Y), width, and height of the upper-left vertex of the Rectangle object *.

      * * Rectangle rect = new Rectangle (x, y, width, height);
      Provides a bufferedimage that is used as a target for decoding pixel data.

      Param.setsourceregion (rect);
       /** * uses the provided imagereadparam to read the object specified by the index imageindex and returns * * it as a complete bufferedimage.

      * * BufferedImage bi = reader.read (0, param);
      Save the new picture Imageio.write (bi, "jpg," "subpath");
      File File = new file (subpath); RetUrn file;
      Finally {if (is!= null) is.close ();
    if (IIS!= null) Iis.close ();

 }

  }

}

Summary of problems encountered:

-cropping picture offset phenomenon
WORKAROUND: Use the compressed picture to collect the trim coordinate information
-multipartfile and file transform each other

The first method:

 multipartfile file = xxx; 
    Commonsmultipartfile cf= (commonsmultipartfile) file; 
    Diskfileitem fi = (Diskfileitem) cf.getfileitem ();

    File f = fi.getstorelocation ();

A file is generated in the temporary folder of the project's root directory;

The second method:

TransferTo (File dest);

A new file is generated in the project;

The third method:

File F = (file) XXX can be strongly turned. If you are configuring Multipartresolver, you will report an exception with a type conversion failure.

<bean id= "Multipartresolver" class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" >
   <property name= "maxuploadsize" value= "104857600"/> <property name=
    "maxinmemorysize" value= "4096" />
  </bean>

Never tried;

The fourth method:

Workbook wb = Workbook.getworkbook (XXX. getInputStream ());

Convert to input stream, direct read;

The Fifth method:

byte[] buffer = myfile.getbytes ();

First converted to byte array, not tried;

The Sixth method:

Turn directly into an input stream

Multipartfile file=xxx;
 is = File.getinputstream ();
 src = Javax.imageio.ImageIO.read (is);
 RET = Src.getwidth (null); Get Source image width

reference materials:
JCOP API:http://code.ciaoca.com/jquery/jcrop/.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.