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之间,若压缩尺寸过小,建议压缩质量设为最高1f
	        encoder.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,否则上传失败。

猜你喜欢

转载自blog.csdn.net/rexueqingchun/article/details/81475660
今日推荐