Artikel ini berbagi kasus lengkap mengunggah gambar di Javaweb untuk referensi. Konten spesifiknya adalah sebagai berikut
Ide Implementasi
• Gunakan plugin jcrop untuk memotong koordinat gambar di ponsel Anda
• Lewati parameter yang dikumpulkan ke latar belakang, gunakan objek grafik java untuk menggambar gambar untuk memotong
◦ Background Processing Flow:
1. Kompres gambar yang diunggah secara proporsional dan unggah ke server file, dan simpan gambar terkompresi di direktori sementara lokal.
2. Gema gambar terkompresi ke halaman, gunakan jcrop untuk memotong, dan klip koordinat pada telepon (x, y, lebar, tinggi)
■@Paramx Target Slice Start Point Koordinat x
■@param y Titik awal slice target koordinat y
■@Param Width Width Slice Target ■@Param Tinggi Tinggi Slice Target
3. Pemrosesan di belakang panggung pemangkasan dan pengunggahan
Halaman JSP
<%@ 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> Unggah avatar pengguna </title> <tautan href = "$ {pagecontext.request.contextPath} /js/cutimg/css/master.css" rel = "stylesheet"//> href = "$ {pageContext.Request.contextPath} /js/cutimg/css/upload.css" rel = "stylesheet"/> <tautan href = "$ {pagecontext.request.contextpath} /js/cutimg/cull = /> <link href = "$ {pagecontext.Request.contextPath} /js/cutimg/css/jquery.jcrop.css" rel = "stylesheet"/</head> <body> <vect "pos" unggah " <dv> <div id = "pic2"> <div id = "unggahfile"> <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" IMGWIDTH "" IMGWIDTH "" IMGWIDTH "" IMGWIDTH "IMGWIDTH" IMGWIDTH "IMGHEIDTH" IMGHEIDTH " <img id = "preview_1" src = "$ {pagecontext.Request.contextPath} /images/4-3.jpg"/> </div> <p> 400 x 300 piksel </p> <%-<v> <img id = "preview_2" src = $ {pageContext.Request.contextPath} /Images/4-3.jpg/> </div> <p> 80 x 80 piksel </p>-%> <p> Seret atau zoom untuk menghasilkan avatar yang memuaskan </p> </div> <%-<v div id = "img_description" 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"/> <v> <div id = "saveImage"> <a href = "javascript :;" style = "Color: Red"> Simpan avatar </a> </div> </div> </form> </div> </body> <script type = "text/javascript" src = "$ {pagecontext.ripest.contextPath} /js/jquery.form.js"> </script> script> Tips = " src = "$ {pageContext.Request.contextPath} /js/jQuery.validate.min.js"> </script> <script = "text/javascript" src = "$ {pagecontext.ripest.contextPath}/jck.jk.js"> {pagecontext.rips.contextPath}/jck = jck = jck = "jcrips.ccrips.ccrips.ccrips.ccrips.ccrips. src = "$ {pageContext.Request.contextPath} /js/check.js"> </script> <script src = "$ {pagecontext.Request.contextPath} /js/cutimg/js/jQuery-.7.1.min.js src = "$ {pageContext.Request.contextPath} /js/cutimg/js/jquery.form.js" type = "text/javascript"> </script> <skrip src = "$ {pagecontext.request.contextpath}/jilput/cuPut/custext type = "Text/JavaScript"> </script> <script src = "$ {pagecontext.Request.contextPath} /js/cutimg/js/jquery-custom-file-input.js" type = "text/javascript"> </script> <skrip src = "$ {pageContext.Request.contextPath} /js/cutimg/js/jquery.jcrop.js" type = "text/javascript"> </script> <script.jin.jin "$ {pagecontext.request.contextpath}/JNMG.JIM.JYM.JYM.JY.JY.JYJY.JEY.JEY.JEY.JEY type = "text/javascript"> </script> <script src = "$ {pagecontext.Request.contextPath} /js/cutimg/js/jquery.rollbar.min.js" type = "text/javascript"> </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"> FOTOS.JCORPWIDTH = 400;//CHROP SELEKSI BOX WELDTH FOTOS.JCORPREIGHT = 300; "80"]; // Ukuran gambar "lebar" array, tentukan lebar gambar yang berbeda dari besar ke kecil sesuai dengan jumlah gambar // foto. Foto.uPload_FileTextId = "upText"; // Unggah tombol komponen Teks ID Teks. "OriginalImg"; // Basis ID Foto ID.upload_reloadid = "up_reload"; // REUPLOAD Foto ID Komponen.Upload_PicValueID = "picval"; // unggah foto konten gambar ID. photos.uPload_picimgheight = "imgheight"; // gambar dasar yang diunggah foto tinggi. "OrigpicVal"; // ID Konten Gambar Asli Ketika halaman lain memasukkan foto.Upload_rollbarid = "pic2"; // Foto ID Scrollbar Kustom.uPload_SaveID = "SaveImage"; // Gambar Penghemat Gambar "Multiple Pictures dari Multipe dari Small Pictures of the Differtix =" Preview _ "; // Gambar Prefix. (Mulai dari 1), Contoh: id = "photos_preview1" ... photos.parentfileImgid = "imgurl"; // photos control photos.parentfileValueD = "imgid"; // pitame picture id alamat control photo.xid = "x"; // x foto. Foto.uptext_format = "Maaf, hanya format JPG, PNG, dan BMP yang didukung untuk saat ini"; // Format Gambar Teks Verifikasi/*Foto.uptext_size = "Maaf, ukuran gambar tidak dapat melebihi kesalahan 2m"; // gambar ukuran gambar/*foto. "/Enterprise/FileCheck"; // alamat foto.url_upload = "/enterprise/unggahphoto? Up = original"; // unggah gambar memuat gambar gambar dasar.url_reload = ""; // muat ulang alamat foto.url_save = "/enterprise/saveImg? UP = save = save"; // alamat gambar.Latar belakang kode java
Alat Unggah Gambar
Paket com.shengya.service.utils; import com.shengya.service.imgcontants; impor org.apache.commons.fileupload.disk.diskfileItem; impor org.springframework.web.multipart.multipartfile; impor; impor org.springframework.web.multipart.commons.Commonsmultipartfile; impor sun.misc.base64encoder; impor javax.crypto.mac; impor javax.crypto.secretkey; impor javax.crypto.spec.secretkeyspec; javax.imageio.imagereadparam; impor java.awt.*; impor java.awt.geom.affinetransform; impor java.awt.image.affinetransformop; impor java.awt.image.bufferedimage; impor java.io. java.net.urlencoder; import java.util.arraylist;/** * @author darcy * dibuat oleh administrator pada 2016/6/17. */unggah kelas publik {// 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?"; URL string statis akhir publik = imgcontants.img_upload + "/file/unggah?"; public final static string fileUrl = imgcontants.img_upload + "/file/unggahfile?"; string statis final publik vediourl = imgcontants.file_upload + "/file/unggah?"; string statis final publik cropurl = imgcontants.img_upload + "/file/cropimage?"; private static byte [] readAsbyTeArr (inputStream adalah) {bytearrayoutputStream baos = new bytearrayoutputStream (); coba {byte [] bytes = byte baru [1024]; panjang int = 0; while ((length = is.read (bytes))! = -1) {Baos.write (bytes, 0, length); } return baos.tobyteArray (); } catch (Exception e) {E.PrintStackTrace (); } akhirnya {coba {baos.close (); } catch (ioException e) {e.printstacktrace (); }} return null; } / ** * Unggah gambar * * @param File * / Public Static String SubmitImage (File File) melempar UnsupportedEncodingException {String FileName = urlencoder.encode (file.getName (), "UTF-8"); long filessize = file.length (); boolean isresuffix = true; tinggi int = 0; Int Width = 500; String mark = "t"; Mode String = "W"; String url = tanda (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; coba {bin = baru bufferedInputStream (fileInputStream baru (file)); conn = (httpurlconnection) URL baru (url) .openconnection (); Conn.SetConnectTimeout (15000); Conn.setRequestMethod ("Post"); Conn.SetDoOutput (true); // conn.setFixedLengthStreamingMode (file.length ()); conn.setRequestProperty ("tipe konten", "Aplikasi/X-WWW-Form-Urlencoded"); conn.setRequestProperty ("Content-Length", File.length () + ""); // conn.setRequestProperty ("range", "bytes ="+""); // Atur pengkodean karakter httpurlConnection conn.setRequestProperty ("AcCECT-charset", "UTF-8"); outstream = conn.getoutputStream (); byte [] buf = byte baru [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 = string baru (data1); instream.close (); mengembalikan json; } else {inputStream instream = conn.getInputStream (); byte [] data1 = readasByTeArr (instream); String json = string baru (data1); instream.close (); mengembalikan json; }} catch (Exception e) {e.printstacktrace (); } akhirnya {coba {if (outstream! = null) {outstream.close (); }} catch (ioException e) {E.PrintStackTrace (); }} return null; } / ** * Unggah gambar * * @param File * / Public Static String SubmitWebImage (File MultiPartFile) melempar UnsupportedencodingException {String fileName = urlencoder.encode (file.getoriginalFileName (), "UTF-8"); long filessize = file.getSize (); boolean isresuffix = true; tinggi int = 0; Int Width = 500; String mark = "t"; Mode String = "W"; String url = tanda (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; coba {bin = baru bufferedInputStream (file.getInputStream ()); conn = (httpurlconnection) URL baru (url) .openconnection (); Conn.SetConnectTimeout (15000); Conn.setRequestMethod ("Post"); Conn.SetDoOutput (true); // conn.setFixedLengthStreamingMode (file.length ()); conn.setRequestProperty ("tipe konten", "Aplikasi/X-WWW-Form-Urlencoded"); conn.setRequestProperty ("Content-Length", File.getSize () + ""); // conn.setRequestProperty ("range", "bytes ="+""); // Atur pengkodean karakter httpurlConnection conn.setRequestProperty ("AcCECT-charset", "UTF-8"); outstream = conn.getoutputStream (); byte [] buf = byte baru [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 = string baru (data1); instream.close (); mengembalikan json; } else {inputStream instream = conn.getInputStream (); byte [] data1 = readasByTeArr (instream); String json = string baru (data1); instream.close (); mengembalikan json; }} catch (Exception e) {e.printstacktrace (); } akhirnya {coba {if (outstream! = null) {outstream.close (); }} catch (ioException e) {E.PrintStackTrace (); }} return null; } / ** * Unggah video * * @param file * / public static String submitradio (file multipartFile) melempar pengecualian {string url = Signradio (radiourl); System.out.println ("URL:" + URL); HttpurlConnection conn = null; OutputStream outstream = null; BufferedInputStream bin = null; coba {bin = baru bufferedInputStream (file.getInputStream ()); conn = (httpurlconnection) URL baru (url) .openconnection (); Conn.SetConnectTimeout (15000); Conn.setRequestMethod ("Post"); Conn.SetDoOutput (true); conn.setRequestProperty ("tipe konten", "Aplikasi/X-WWW-Form-Urlencoded"); conn.setRequestProperty ("Content-Length", File.getSize () + ""); Conn.setRequestProperty ("Accept-Charset", "UTF-8"); outstream = conn.getoutputStream (); byte [] buf = byte baru [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 = string baru (data1); instream.close (); mengembalikan json; } else {inputStream instream = conn.getInputStream (); byte [] data1 = readasByTeArr (instream); String json = string baru (data1); instream.close (); mengembalikan json; }} catch (Exception e) {e.printstacktrace (); } akhirnya {coba {if (outstream! = null) {outstream.close (); }} catch (ioException e) {E.PrintStackTrace (); }} return null; } /** * Unggah resume snapshot * * @param fileName * @param konten * @return * @throws UnsupportedencodingException * /public static String SubmitFile (string fileName, content string) melempar UnsupportedencodingException {// content = urlencoder.encode (konten, " fileName = urlencoder.encode (nama file, "UTF-8"); byte [] contentBytes = content.getBytes (); long filessize = contentBytes.length; boolean isresuffix = true; tinggi int = 0; Int Width = 500; String mark = "t"; Mode String = "W"; String url = tanda (fileurl) + "& channelno = muying_android" + "& filename =" + fileName + "& fileSize =" + FileSize + "& isResuffix =" + isResuffix + "& height =" + height + "& width =" + width + "& Mark =" + Mark + "& Mode =" System.out.println ("URL:" + URL); HttpurlConnection conn = null; OutputStream outstream = null; BufferedInputStream bin = null; coba {conn = (httpUrlConnection) URL baru (url) .openconnection (); Conn.SetConnectTimeout (15000); Conn.setRequestMethod ("Post"); Conn.SetDoOutput (true); // conn.setFixedLengthStreamingMode (file.length ()); conn.setRequestProperty ("tipe konten", "Aplikasi/X-WWW-Form-Urlencoded"); Conn.setRequestProperty ("Content-Length", Content.Length () + ""); // conn.setRequestProperty ("range", "bytes ="+""); // Atur pengkodean karakter httpurlConnection conn.setRequestProperty ("AcCECT-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 = string baru (data1); instream.close (); mengembalikan json; } else {inputStream instream = conn.getInputStream (); byte [] data1 = readasByTeArr (instream); String json = string baru (data1); instream.close (); mengembalikan json; }} catch (Exception e) {e.printstacktrace (); } akhirnya {coba {if (outstream! = null) {outstream.close (); }} catch (ioException e) {E.PrintStackTrace (); }} return null; } / *** Unggah lampiran** @return json string* @throws unsportedencodingException* / public static String SubmitFile (file multipartFile) melempar UnsupportedEncodingException {string fileName = urlencoder.encode (file.getoriginalFileName (), ""); long filessize = file.getSize (); boolean isresuffix = true; tinggi int = 0; Int Width = 500; String mark = "t"; Mode String = "W"; String url = tanda (fileurl) + "& channelno = muying_android" + "& filename =" + fileName + "& fileSize =" + FileSize + "& isResuffix =" + isResuffix + "& height =" + height + "& width =" + width + "& Mark =" + Mark + "& Mode =" System.out.println ("URL:" + URL); HttpurlConnection conn = null; OutputStream outstream = null; BufferedInputStream bin = null; coba {bin = baru bufferedInputStream (file.getInputStream ()); conn = (httpurlconnection) URL baru (url) .openconnection (); Conn.SetConnectTimeout (15000); Conn.setRequestMethod ("Post"); Conn.SetDoOutput (true); // conn.setFixedLengthStreamingMode (file.length ()); conn.setRequestProperty ("tipe konten", "Aplikasi/X-WWW-Form-Urlencoded"); conn.setRequestProperty ("Content-Length", File.getSize () + ""); // conn.setRequestProperty ("range", "bytes ="+""); // Atur pengkodean karakter httpurlConnection conn.setRequestProperty ("AcCECT-charset", "UTF-8"); outstream = conn.getoutputStream (); byte [] buf = byte baru [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 = string baru (data1); instream.close (); mengembalikan json; } else {inputStream instream = conn.getInputStream (); byte [] data1 = readasByTeArr (instream); String json = string baru (data1); instream.close (); mengembalikan json; }} catch (Exception e) {e.printstacktrace (); } akhirnya {coba {if (outstream! = null) {outstream.close (); }} catch (ioException e) {E.PrintStackTrace (); }} return null; } private static string Sign (String baseUrl) melempar UnsupportedEncodingException {long mata uang = System.CurrentTimeMillis (); waktu panjang = mata uang / 1000; String Data = "ActionName = unggahimage" + "& 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) melempar Exception {Long CurrencyBTime = System.CurrentTimeMillis (); Data String = "SecretKey = F1B79C865C424BE46183A2F0A49A0F15" + "& timestamp =" + mata uang; 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"); pengembalian URL + Data + "& Signature =" + Signature; } private static string hmac_sha1 (tombol string, string dataS) {string restring = ""; coba {datasas = data.replace ("%3a", "%3a"); data = data.replace ("%2f", "%2f"); data = data.replace ("%3D", "%3D"); byte [] data = key.getBytes ("UTF-8"); // Bangun kunci berdasarkan array byte yang diberikan, dan parameter kedua menentukan nama algoritma utama Secretkey Secretkey = new Secreteyspec (data, "hmacsha1"); // Hasilkan objek Mac dengan algoritma Mac Mac Mac = mac.getInstance yang ditentukan ("hmacsha1"); // inisialisasi objek Mac dengan kunci mac.init (SecretKey); byte [] text = datas.getBytes ("UTF-8"); // Byte Operasi Mac Lengkapi [] Text1 = Mac.Dofinal (Teks); pembatasan = base64Encoder baru (). EncodeBuffer (text1); pembatasan = urlencoder.encode (pembatasan, "UTF-8"); restring = restring.replace ("%0a", ""); restring = restring.replace ("%0d", ""); } catch (Exception e) {E.PrintStackTrace (); } return restring; }/** * Unggah gambar cropped * zxiao 2016/09/01 * * @param fileid */string statis public SubmittedCutedWebImage (file multipartFile, string fileid, string x, string y, string w, string h) melempar unsupportedEncodingException {string fileid = fileid; String [] cropWidths = string baru [] {"50"}; // crop width // daftar <string> daftar = daftar baru <string> (); // Daftar <String> Daftar = ArrayList baru <string> (5); ArrayList <String> listCropWidths = ArrayList baru <string> (); listCropwidths.add ("400"); // string [] cropheights = string baru [] {"50"}; // CROP tinggi arraylist <string> listCropheights = new ArrayList <String> (); ListCropheights.add ("300"); int cropx = integer.parseint (x); // crop x koordinat int cropy = integer.parseint (y); // crop y koordinat // string [] cropFixs = new string [] {"l"}; // crop Mark atur arraylist <string> listCropFixs = new Arraylist <); listCropfixs.add ("l"); String Sourcesuffix = "jpg"; // peta dasar SUFFIX STRINGFIX = ""; // Logo peta dasar/* boolean isResuffix = true; tinggi int = 1000; Int Width = 750; String mark = "t"; Mode string = "w";*/ string url = tanda (cropurl) + "fileid =" + fileid + "& cropwidths =" + listCropwidths + "& cropheights =" + listCropheight + "& cropx =" + cropx + "& cropy =" + cropy + "& cropFixs =" " + cropx +" & cropy = " + cropy +" & cropFixs = "" + " + cropx +" & cropy = " + cropy +" & cropFixs = "" " + cropx +" & cropy = " + cropy +" & cropFixs = "" "& SourceFix =" + SourceFix; System.out.println ("URL:" + URL); HttpurlConnection conn = null; OutputStream outstream = null; BufferedInputStream bin = null; coba {bin = baru bufferedInputStream (file.getInputStream ()); conn = (httpurlconnection) URL baru (url) .openconnection (); Conn.SetConnectTimeout (15000); Conn.setRequestMethod ("Post"); Conn.SetDoOutput (true); // conn.setFixedLengthStreamingMode (file.length ()); conn.setRequestProperty ("tipe konten", "Aplikasi/X-WWW-Form-Urlencoded"); conn.setRequestProperty ("Content-Length", File.getSize () + ""); // conn.setRequestProperty ("range", "bytes ="+""); // Atur pengkodean karakter httpurlConnection conn.setRequestProperty ("AcCECT-charset", "UTF-8"); outstream = conn.getoutputStream (); byte [] buf = byte baru [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 = string baru (data1); instream.close (); mengembalikan json; } else {inputStream instream = conn.getInputStream (); byte [] data1 = readasByTeArr (instream); String json = string baru (data1); instream.close (); mengembalikan json; }} catch (Exception e) {e.printstacktrace (); } akhirnya {coba {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 = file baru (folder); // Jika folder tidak ada, buat if (! Tempdir .exists () &&! Tempdir .isdir ()) {// system.out.println ("// tidak ada"); tempdir .mkdir (); } // string file sementara terkompresi srcpath = folder+"scaletemp.jpg"; // Dapatkan sufiks file/*file unggahfile = file baru (srcpath); InputStream inputStream = file.getInputStream (); FileInputStream fs = (FileInputStream) InputStream; String srcimg = urlencoder.encode (file.getoriginalFileName (), "UTF-8"); String suffix = srcimg.substring (srcimg.LastIndexOf (".")+1);*/// Potong gambar cutimgutils o = cutimgutils baru (x, y, w, h); o.setsrcpath (srcpath); o.setsubpath (folder+"uptemp.jpg"); File tempfile = o.cut ("jpg"); String s = kirimImage (tempfile); kembali S; }/** * Dapatkan lebar gambar yang diunggah * Zxiao 2016/09/09 * @param file * @return */int statis publik getimgwidth (file multipartfile) melempar ioException {inputStream is = null; BufferedImage SRC = NULL; int ret = -1; coba {is = file.getInputStream (); src = javax.imageio.imageio.read (IS); ret = src.getWidth (null); // Dapatkan lebar gambar sumber adalah.close (); } catch (Exception e) {E.PrintStackTrace (); } return ret; }/** * Dapatkan gambar yang diunggah tinggi * zxiao 2016/09/09 * @param file * @return */int statis public getimgheight (file multipartfile) {inputStream is = null; BufferedImage SRC = NULL; int ret = -1; coba {is = file.getInputStream (); src = javax.imageio.imageio.read (IS); ret = src.getHeight (null); // Dapatkan ketinggian gambar sumber adalah.close (); } catch (Exception e) {E.PrintStackTrace (); } return ret; } /*** Skala gambar (penskalaan berdasarkan tinggi dan lebar)* Objek file file @param* @param Hasil skala alamat gambar* @param tinggi skala tinggi* @param lebar lebar skala* @param bb apakah perlu untuk mengisi ketika skala tidak benar: true adalah isi; Salah tidak diisi; */ skala void statis publik (file multipartfile, hasil string, tinggi int, lebar int, boolean bb) {coba {rasio ganda = 0,0; // scaling/*commonsmultipartfile cf = (commonsmultipartfile) file; Diskfileitem fi = (diskfileItem) cf.getFileItem (); File f = fi.getStoreLocation ();*/// file f = file baru (srcimageFile); InputStream inputStream = file.getInputStream (); BufferedImage BI = ImageIO.READ (InputStream); Item gambar = bi.getScaledInstance (lebar, tinggi, bi.scale_smooth); // Hitung skala if ((bi.getHeight ()> height) || (bi.getWidth ()> width)) {if (bi.getHeight ()> bi.getWidth ()) {ratio = (integer baru (tinggi)). Doublevalue () / bi.getheight (); } else {rasio = (integer baru (lebar)). doublevalue () / bi.getWidth (); } Affinetransformop op = affinetransformop baru (affinetransform .getScaleInstance (rasio, rasio), null); item = op.filter (bi, null); } if (bb) {// Isi gambar bufferedImage = BufferedImage baru (lebar, tinggi, bufferedImage.type_int_rgb); Graphics2d G = Image.Creategraphics (); G.SetColor (Color.White); g.fillrect (0, 0, lebar, tinggi); if (width == item.getWidth (null)) g.drawimage (itemp, 0, (tinggi - 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 = gambar; } Item ImageIO.Write ((BufferedImage), "JPG", File Baru (Hasil)); } catch (ioException e) {e.printstacktrace (); }} public static void main (string [] args) {coba {/* file file = file baru ("e: // bole // doc // document antarmuka layanan // bole antarmuka layanan deskripsi v1.0.docx"); System.out.println ("File =" + file); String json = submitFile (file); System.out.println ("json =" + json);*/} catch (Exception e) {e.printstacktrace (); }}} Alat tanam gambar
Paket com.shengya.service.utils; impor javax.imageio.imageio; impor javax.imageio.imagereadparam; impor javax.imageio.imagereader; impor javax.imageo.stream.imageinputstream; impor java.awt.*; impor java.awt.awt.awt. java.io.fileInputStream; import java.io.ioException; import java.util.iterator;/*** dibuat oleh administrator pada 2016/9/1. */cutimgutils kelas publik {// === Nama jalur gambar sumber seperti: c: /1.jpg Private String SrcPath; // === Nama jalur penyimpanan gambar klip. Misalnya: 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 mengoordinasikan int x x; int y private; // === Slift Point Width Private Int Width; Tinggi int pribadi; cutimgutils publik () {} cutimgutils publik (int x, int y, lebar int, tinggi int) {if (x <0) {x = 0; } else {this.x = x; } if (y <0) {y = 0; } else {this.y = y; } this.width = lebar; this.height = tinggi; } /** * * Potong gambar dan simpan gambar baru setelah dipangkas. */ cut file publik () melempar ioException {fileInputStream adalah = null; ImageInputStream IIS = null; coba {// Baca file gambar adalah = FileInputStream baru (SRCPath); /** * * Mengembalikan iterator yang berisi semua imagereader terdaftar saat ini, yang mengklaim dapat memecahkan kode format yang ditentukan. Parameter: FormatName - Berisi nama format informal. * *; Pembaca imagereader = it.next (); // Dapatkan stream gambar IIS = imageIO.CreateMageInputStream (IS); /** * * <p> * IIS: Baca sumbernya. Benar: Cari saja maju saja * </p> *. Tandai sebagai 'Pencarian ke depan saja'. * * Pengaturan ini berarti bahwa gambar yang termasuk dalam sumber input hanya akan dibaca secara berurutan, yang memungkinkan pembaca * * untuk menghindari di -cache porsi input yang berisi data yang terkait dengan gambar yang dibaca sebelumnya. */ reader.setInput (IIS, true); /** * * <p> * Kelas yang menjelaskan cara mendekode aliran * <p> *. Digunakan untuk menentukan cara mengonversi gambar atau set gambar dari aliran dalam konteks kerangka I/O * Image Java saat input. Plugin untuk format gambar tertentu * * * Sebuah instance ImagereAdparam akan dikembalikan dari metode GetDefaultreadParam implementasi Imagereader. */ Imagereadparam param = reader.getDefaultreadparam (); /** * * Area tanaman gambar. Rectangle menentukan area dalam ruang koordinat, yang dapat ditentukan oleh koordinat (x, y), lebar, dan tinggi simpul kiri atas objek persegi panjang **. */ Persegi panjang rect = persegi panjang baru (x, y, lebar, tinggi); // Berikan bufferedImage untuk menggunakannya sebagai target untuk decoding data piksel. param.setsourceregion (rect); /** * Gunakan ImageReAdParam yang disediakan untuk membaca objek yang ditentukan dengan mengindeks ImageIndex dan Return * * sebagai bufferedImage lengkap. */ BufferedImage bi = reader.read (0, param); // Simpan gambar baru Imageo.write (BI, "JPG", File Baru (Subpath)); File file = file baru ("Subpath"); pengembalian file; } akhirnya {if (is! = null) is.close (); if (iis! = null) iis.close (); }} cut cut (string suffix) melempar ioException {fileInputStream adalah = null; ImageInputStream IIS = null; Coba {// Baca file gambar adalah = FileInputStream baru (srcpath); // is = inputStream; /** * Mengembalikan iterator yang berisi semua imagereaders terdaftar saat ini * * mengklaim dapat memecahkan kode format yang ditentukan. Parameter: FormatName - Berisi nama format informal. * *; */ String suffixname = null; if (suffix.equals ("gif")) {suffixname = "gif"; } else if (suffix.equals ("png")) {suffixname = "png"; } else {suffixname = "jpg"; } Iterator <ImageReAder> it = Imageo .getImagereadersByFormatname (suffixname); Pembaca imagereader = it.next (); // Dapatkan stream gambar IIS = imageIO.CreateMageInputStream (IS); /** * * <p> * IIS: Baca sumbernya. Benar: Cari saja maju saja * </p> *. Tandai sebagai 'Pencarian ke depan saja'. * * Pengaturan ini berarti bahwa gambar yang termasuk dalam sumber input hanya akan dibaca secara berurutan, yang memungkinkan pembaca * * untuk menghindari di -cache porsi input yang berisi data yang terkait dengan gambar yang dibaca sebelumnya. */ reader.setInput (IIS, true); /** * * <p> * Kelas yang menjelaskan cara mendekode aliran * <p> *. Digunakan untuk menentukan cara mengonversi gambar atau set gambar dari aliran dalam konteks kerangka I/O * Image Java saat input. Plugin untuk format gambar tertentu * * * Sebuah instance ImagereAdparam akan dikembalikan dari metode GetDefaultreadParam implementasi Imagereader. */ 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(); }}}遇到的问题总结:
-裁剪图片发生偏移现象<br />解决办法:使用压缩后的图片等比例收集裁切坐标信息
-MultipartFile 和File之间相互转化
第一种方法:
MultipartFile file = xxx; CommonsMultipartFile cf= (CommonsMultipartFile)file; DiskFileItem fi = (DiskFileItem)cf.getFileItem(); File f = fi.getStoreLocation();
会在项目的根目录的临时文件夹下生成一个文件;
第二种方法:
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); // 得到源图宽
Referensi:
jcop api:http://code.ciaoca.com/jquery/jcrop/.
Di atas adalah semua konten artikel ini. Saya berharap ini akan membantu untuk pembelajaran semua orang dan saya harap semua orang akan lebih mendukung wulin.com.