Java上传图片预览并通过JS压缩

1.前端上传图片JS压缩

<%@ 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;  
            $("#sfzzm_name").val(reader.fileName);
            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';    
                    }  
                	//压缩照片
                    var base64 = yszp(img,this);
                    $("#sfzzm_base64").val(base64);    
                }   
            }    
        }    
    }    
                 
})

//压缩照片
function yszp(img,ThisPic){
	//缩放图片需要的canvas
	var canvas = document.createElement('canvas');
	var context = canvas.getContext('2d');
	// 图片原始尺寸
	 var originWidth = ThisPic.width;
	 var originHeight = ThisPic.height;
	 // 最大尺寸限制
	 var maxWidth = 200, maxHeight = 200;
	 // 目标尺寸
	 var targetWidth = originWidth, targetHeight = originHeight;
	 // 图片尺寸超过200x200的限制
	 if (originWidth > maxWidth || originHeight > maxHeight) {
	     if (originWidth / originHeight > maxWidth / maxHeight) {
	         // 更宽,按照宽度限定尺寸
	         targetWidth = maxWidth;
	         targetHeight = Math.round(maxWidth * (originHeight / originWidth));
	     } else {
	         targetHeight = maxHeight;
	         targetWidth = Math.round(maxHeight * (originWidth / originHeight));
	     }
	 }	     
	 // canvas对图片进行缩放
	 canvas.width = targetWidth;
	 canvas.height = targetHeight;
	 // 清除画布
	 context.clearRect(0, 0, targetWidth, targetHeight);
	 // 图片压缩
	 context.drawImage(img, 0, 0, targetWidth, targetHeight);
	 // 返回压缩后的base64
	 return canvas.toDataURL();
}
                
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="hidden" id="sfzzm_name" name="sfzzm_name">
	<input type="hidden" id="sfzzm_base64" name="sfzzm_base64">
	<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.后端保存图片

@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");
		String sfzzm_base64 = request.getParameter("sfzzm_base64");
		String sfzzm_name = request.getParameter("sfzzm_name");
		String suffix = sfzzm_name.substring(sfzzm_name.lastIndexOf(".") + 1);
		String filename = System.currentTimeMillis() + "." + suffix;
		String path = filePath + "/ajbj/zm/"+filename;
		sfzzm_base64 = sfzzm_base64.split(",")[1];
		GenerateImage(sfzzm_base64, path);
		return mv;
	}
	
	/**
	 * @Description: 将base64编码字符串转换为图片
	 * @param imgStr base64编码字符串
	 * @param path 图片路径-具体到文件
	*/ 
    public static boolean GenerateImage(String imgStr,String imgFilePath){     
        if (imgStr == null) //图像数据为空  
            return false;  
        BASE64Decoder decoder = new BASE64Decoder();  
        try{  
            //Base64解码  
            byte[] b = decoder.decodeBuffer(imgStr);  
            for(int i=0;i<b.length;++i){  
                if(b[i] < 0){//调整异常数据  
                    b[i] += 256;  
                }  
            }  
            OutputStream out = new FileOutputStream(imgFilePath);      
            out.write(b);  
            out.flush();  
            out.close();  
            return true;  
        }   
        catch (Exception e){  
            return false;  
        }  
    }

猜你喜欢

转载自blog.csdn.net/rexueqingchun/article/details/81476802