使用jFinal和Jcrop实现头像上传功能详解编程语言

使用jFinal和Jcrop实现常用的头像上传和裁剪功能。java代码以及对应的javascript代码如下:

 

上传头像页面对应的html    

<div class="content2"> 
    <div class="formside"> 
        <div id="info" class="info" style="color:red;"></div> 
        <form id="uploadImageForm" action="/user/updateTx" method="post" enctype="multipart/form-data"> 
             <div style="height:30px;align:center"> 
         图片文件(不得超过2M)<input id="image" name="image"  type="file" style="width:300px;overflow: hidden;border:none;/> 
	                     <input id="add" type="button"  value="上传" class="btn"/> 
             </div> 
       </form> 
       <div style='max-width:730px;'><img id="currentPhoto" src="" style='display:none;max-width:730px;'></img></div> 
       <input id="save" type="button"  value="保存头像" class="btn" style='display:none;'/> 
    </div> 
</div> 
<form id='form_save' action="/user/save_portrait" style='display:none;'> 
    <input type='hidden' id='img_left' name='left' value='0'/> 
    <input type='hidden' id='img_top' name='top' value='0'/> 
    <input type='hidden' id='img_width' name='width' value='0'/> 
    <input type='hidden' id='img_height' name='height' value='0'/> 
</form>

javascript代码    

<script src="/js/jquery.js" type="text/javascript" ></script> 
<script src="/js/jquery.form.js" type="text/javascript" ></script> 
<script src="/js/jquery.Jcrop.min.js" type="text/javascript" ></script> 
<script type="text/javascript"> 
$("#add").click(function(){ 
	if($("#image").val() == ""){ 
		alert("请选择一个图片文件,再点击上传。"); 
		return; 
	}else{ 
	    $("#uploadImageForm").ajaxSubmit({ 
	    	dataType: 'json', 
	        success:function(result,status){ 
	        	if(result.success){ 
	                var url=result.path; 
	                $("#currentPhoto").attr("src",url); 
	                $("#currentPhoto").show(); 
	                $("#save").show(); 
	                $("#add").hide(); 
	                $('#currentPhoto').Jcrop({ 
	                	setSelect: [ 10, 10, 210, 210 ], 
                        aspectRatio: 1, 
	                	onChange: showCoords, 
                        onSelect: showCoords 
	                }); 
	            }else{ 
	                alert(result.msg); 
	            } 
	        }, 
		    error: function(result,status,e){   
		        alert(status);   
		    } 
	    });   
	    return false;    
	} 
});   
 
function showCoords(c){ 
    $('#img_left').val(c.x); 
    $('#img_top').val(c.y); 
    $('#img_width').val(c.w); 
    $('#img_height').val(c.h); 
}; 
 
 
$('#save').click(function(){ 
    var args = 'left='+$("#img_left").val()+'&top='+$("#img_top").val()+'&width='+$("#img_width").val()+'&height='+$("#img_height").val(); 
    $.ajax({ 
        url:'/user/saveTx?'+args, 
        type:'post', 
        dataType:'json', 
        success : function(data){ 
            alert(data.msg); 
            location.href="/user"; 
        } 
    }); 
});

点击上传对应的后台java方法    

//上传头像方法实现 
public void updateTx(){ 
		user = getSessionAttr("user"); 
		String path = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); 
		UploadFile file = getFile("image", PathKit.getWebRootPath() + "/temp"); 
		File source = file.getFile(); 
		String fileName = file.getFileName(); 
		String extension = fileName.substring(fileName.lastIndexOf(".")); 
		if(!".png".equals(extension) && !".jpg".equals(extension)){ 
			setAttr("success", false); 
			setAttr("msg", "必须是图片文件才能上传!"); 
		}else if(source.length()>MAX_SIZE){ 
			setAttr("success", false); 
			setAttr("msg", "图片大小不能超过2M!"); 
		}else{ 
			fileName = user.getInt("Id") + "-" + path + "-" + CommonUtil.generateWord() + extension; 
			try { 
				FileInputStream fis = new FileInputStream(source); 
				File targetDir = new File(PathKit.getWebRootPath() + "/img/u"); 
				if (!targetDir.exists()) { 
					targetDir.mkdirs(); 
				} 
				File target = new File(targetDir, fileName); 
				if (!target.exists()) { 
					target.createNewFile(); 
				} 
				FileOutputStream fos = new FileOutputStream(target); 
				byte[] bts = new byte[300]; 
				while (fis.read(bts, 0, 300) != -1) { 
					fos.write(bts, 0, 300); 
				} 
				fos.close(); 
				fis.close(); 
				setAttr("path", "/img/u/" + fileName); 
				setAttr("success", true); 
				user.set("image", PathKit.getWebRootPath()+"/img/u/" + fileName); 
			} catch (FileNotFoundException e) { 
				setAttr("success", false); 
				setAttr("msg", "上传失败!上传的文件不存在!"); 
			} catch (IOException e) { 
				setAttr("success", false); 
				setAttr("msg", "上传失败,请重新上传!"); 
			} 
		} 
		render(new JsonRender().forIE()); 
	}

头像裁剪完成后保存头像对应的java方法    

public void saveTx() throws IOException{ 
		JSONObject json= new JSONObject(); 
		user = getSessionAttr("user"); 
		int left= getParaToInt("left"); 
		int top= getParaToInt("top"); 
		int width= getParaToInt("width"); 
		int height= getParaToInt("height"); 
		File source = new File(user.getStr("image")); 
		String fileName = source.getName(); 
		 
		boolean isSave = saveImage(source,PathKit.getWebRootPath()+"/img/u/" + fileName,top,left,width,height); 
		if(isSave){ 
			user.set("image", "/img/u/" + fileName); 
			user.update(); 
			json.put("msg", "头像更新成功!"); 
		}else{ 
			json.put("msg", "头像更新失败!"); 
		} 
		 
		renderJson(json); 
		 
	}

对图片进行剪裁的java方法    

/** 
	 * 对图片进行剪裁,只保存选中的区域 
	 * @param img 原图路径 
	 * @param dest 目标路径 
	 * @param top 
	 * @param left 
	 * @param width 
	 * @param height 
	 * @return 
	 * @throws IOException 
	 */ 
	public static boolean saveImage(File img,String dest,int top,int left,int width,int height) throws IOException { 
		File fileDest = new File(dest);      
		if(!fileDest.getParentFile().exists())      
		    fileDest.getParentFile().mkdirs();      
		BufferedImage bi = (BufferedImage)ImageIO.read(img);      
		height = Math.min(height, bi.getHeight());      
		width = Math.min(width, bi.getWidth());      
		if(height <= 0) height = bi.getHeight();      
		if(width <= 0) width = bi.getWidth();      
		top = Math.min(Math.max(0, top), bi.getHeight()-height);      
		left = Math.min(Math.max(0, left), bi.getWidth()-width);      
		        
		BufferedImage bi_cropper = bi.getSubimage(left, top, width, height);      
		return ImageIO.write(bi_cropper, "jpeg", fileDest);      
 }    

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/8543.html

(0)
上一篇 2021年7月18日
下一篇 2021年7月18日

相关推荐

发表回复

登录后才能评论