Java上传图片预览并通过后端压缩
生活随笔
收集整理的這篇文章主要介紹了
Java上传图片预览并通过后端压缩
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.前端上傳圖片預覽
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%String contextPath = request.getContextPath(); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no,width=device-width,height=device-height"> <script src="<%=contextPath%>/js/jquery-1.11.3.js"></script> <title>圖片上傳</title> <style type="text/css"> .float_zm{ float_zm:left; width : 200px; height: 200px; overflow: hidden; border: 1px solid #CCCCCC; border-radius: 10px; padding: 5px; margin: 5px; position:absolute;left:50%;margin-left: -100px;} .result{ width: 200px; height: 200px; text-align: center; box-sizing: border-box; } </style> <script type="text/javascript"> $(function(){var input = document.getElementById("file_input_zm"); if(typeof FileReader==='undefined'){ alert("抱歉,你的瀏覽器不支持 FileReader"); input.setAttribute('disabled','disabled'); }else{ input.addEventListener('change',readFile,false); }function readFile(){ var iLen = this.files.length; var index = 0; for(var i=0;i<iLen;i++){ if (!input['value'].match(/.jpg|.gif|.png|.jpeg|.bmp/i)){ //判斷上傳文件格式 return alert("上傳的圖片格式不正確,請重新選擇"); } /* if (this.files[i].size > 1048576){return alert("上傳的圖片大小超過1M,請重新選擇"); //判斷上傳圖片大小} */ var reader = new FileReader(); reader.index = i; reader.readAsDataURL(this.files[i]); //轉成base64 reader.fileName = this.files[i].name; reader.onload = function(e){ $("#zmtp").empty();var result = '<div class="float_zm"><div onclick="select_zm()" class="result"><img id="sfzzm" src="'+this.result+'" /></div></div>'; $("#zmtp").html(result);var img = document.getElementById('sfzzm');img.onload = function(){ var nowHeight = ReSizePic(this); //設置圖片預覽大小 this.parentNode.style.display = 'block'; var oParent = this.parentNode; if(nowHeight){ oParent.style.paddingTop = (oParent.offsetHeight - nowHeight)/2 + 'px'; } } } } } })function ReSizePic(ThisPic) { var RePicWidth = 200; //目標寬度 var TrueWidth = ThisPic.width; //圖片實際寬度 var TrueHeight = ThisPic.height; //圖片實際高度 if(TrueWidth>TrueHeight){ //寬大于高 var reWidth = RePicWidth; ThisPic.width = reWidth; //垂直居中 var nowHeight = TrueHeight * (reWidth/TrueWidth); return nowHeight; //將圖片修改后的高度返回,供垂直居中用 }else{ //寬小于高 var reHeight = RePicWidth; ThisPic.height = reHeight; } } //選擇照片 function select_zm(){$("#file_input_zm").click(); } //上傳 function myCheck(){var sfzzm = $("#sfzzm").attr("src");if(sfzzm == ''){alert("請選擇照片");return false;}$("#form").submit(); } </script> </head> <body><form id="form" action="wap_ajbj_upload_save.htm" method="post" enctype="multipart/form-data"><input type="file" id="file_input_zm" name="file_input_zm" style="display: none;"/><div id="zmtp" style="width: 100%;height: 240px;position:relative;"> <div class="float_zm"><div class="result" onclick="select_zm()"><img id="sfzzm" name="sfzzm" /><span id="zpbz" style="font-size: 16px;line-height: 200px;">照片(點擊上傳)</span></div> </div></div> <div style="text-align: center;margin: 0 auto;"><button style="width: 80%;" type="button" onclick="myCheck()">上傳</button></div> </form> </body> </html>2.后端壓縮保存圖片
private String filePath = LxwmController.class.getResource("/").getPath().split("WEB-INF")[0]+ "upload/";@RequestMapping(value = "wap_ajbj_upload_save.htm", method = { RequestMethod.GET,RequestMethod.POST })public ModelAndView wap_ajbj_upload_save(MultipartHttpServletRequest request) throws Exception {ModelAndView mv = new ModelAndView("wap/ajbj_index");MultipartFile file = null;String file_ys = "";file = ((MultipartRequest) request).getFile("file_input_zm");if(file != null && !file.isEmpty()){String filename = file.getOriginalFilename(); //獲取文件的名字filename = new String(filename.getBytes("UTF-8"), "UTF-8");String suffix = filename.substring(filename.lastIndexOf(".") + 1);filename = System.currentTimeMillis() + "." + suffix;file_ys = "/ajbj/fm/" + filename;try {//原圖片copyFileRename(file.getInputStream(), filename,filePath + "/ajbj/zm/");} catch (IOException e) {e.printStackTrace();}//壓縮圖片compressImage(file,filePath + file_ys);}return mv;}public static void copyFileRename(InputStream in, String fileName,String myFilePath) throws IOException {FileOutputStream fs = new FileOutputStream(myFilePath + fileName);byte[] buffer = new byte[1024 * 1024];int byteread = 0;while ((byteread = in.read(buffer)) != -1) {fs.write(buffer, 0, byteread);fs.flush();}fs.close();in.close();}//壓縮照片public Boolean compressImage(MultipartFile source_file,String target_path) throws IOException {try { int maxWidth = 400;//限制最大寬int maxHeight = 400;//限制最大高//獲得文件源InputStream ins = source_file.getInputStream();File file = new File(source_file.getOriginalFilename());inputStreamToFile(ins, file);Image img = ImageIO.read(file);int originWidth = img.getWidth(null);int originHeight = img.getHeight(null);int targetWidth = 0;//目標寬int targetHeight = 0;//目標高//寬或者高超過最大上限時進行壓縮if (originWidth > maxWidth || originHeight > maxHeight) {if(originWidth >= originHeight){//橫圖或方圖targetWidth = maxWidth;targetHeight = (int) Math.round(maxWidth * (double)originHeight / (double)originWidth);}else{//豎圖targetHeight = maxHeight;targetWidth = (int) Math.round(maxHeight * (double)originWidth / (double)originHeight);}}BufferedImage tag = new BufferedImage(targetWidth,targetHeight,BufferedImage.TYPE_INT_RGB);tag.getGraphics().drawImage(img,0,0,targetWidth,targetHeight,null);FileOutputStream out = new FileOutputStream(target_path);//JPEGImageEncoder可適用于其他圖片的類型的轉換JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);JPEGEncodeParam encoder_param = JPEGCodec.getDefaultJPEGEncodeParam(tag);encoder_param.setQuality(1f, true);//質量壓縮,范圍為0.1-1之間,若壓縮尺寸過小,建議壓縮質量設為最高1fencoder.setJPEGEncodeParam(encoder_param);encoder.encode(tag);out.close();return true; } catch(Exception e) { return false; } } public static void inputStreamToFile(InputStream ins,File file) {try {OutputStream os = new FileOutputStream(file);int bytesRead = 0;byte[] buffer = new byte[8192];while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {os.write(buffer, 0, bytesRead);}os.close();ins.close();} catch (Exception e) {e.printStackTrace();}}備注:后端壓縮相比前端JS壓縮的優點是不限制文件大小,若通過前端JS壓縮把圖片轉化為base64上傳的話,則必須保證壓縮后的文件小于1.5M,否則上傳失敗。
總結
以上是生活随笔為你收集整理的Java上传图片预览并通过后端压缩的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 出走的门徒之七—驭势 吴甘沙:一步十年
- 下一篇: 拍摄失败导致照片像素低,学会这个可以一键