图片裁剪预览上传

/**
	 * 上传图片到数据库
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("uploadPic")
	public ModelAndView uploadPic(HttpServletRequest request, HttpServletResponse response) throws Exception {
	
		String preUrl = RequestUtil.getPrePage(request);
		
		SysUser currUser = ContextUtil.getCurrentUser();
		String empNum = currUser.getAccount();
		
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		MultipartFile multiFile = multiRequest.getFile("imgfile");
		Map<String,String[]> map = multiRequest.getParameterMap();
		ImageInputStream iis = null;
		
		// 扩展名格式:
		String extName = "";
		String message = "";
		String newName = "";
		boolean flag = true;
		int result = 0;
		
		int x = map.get("top")!=null && !"".equals(map.get("top")[0].trim())?Integer.parseInt(map.get("top")[0]):0;
		int y = map.get("left")!=null && !"".equals(map.get("left")[0].trim())?Integer.parseInt(map.get("left")[0]):0;
		int w = map.get("width")!=null && !"".equals(map.get("width")[0].trim())?Integer.parseInt(map.get("width")[0]):0;
		int h = map.get("height")!=null && !"".equals(map.get("height")[0].trim())?Integer.parseInt(map.get("height")[0]):0;
		
		//取得上传的文件名
		String fileName =  multiFile.getOriginalFilename();
		System.out.println(fileName);
		if(fileName!=null && !"".equals(fileName.trim())){
			//上传文件文件的大小
			long size = multiFile.getSize();
			if(size > (1024 * 1024 * 2)){
				message = "toolarge";
				flag = false;
			}
			//定义允许上传的文件类型
			List<String> fileTypes = new ArrayList<String>();
			fileTypes.add(".jpg");
			fileTypes.add(".jpeg");
			fileTypes.add(".gif");
			fileTypes.add(".png");
			fileTypes.add(".bmp");
			extName = fileName.substring(fileName.lastIndexOf("."));
			if(!fileTypes.contains(extName.toLowerCase())){
				message = "invalidformat";
				System.out.println(message);
				flag = false;
			}
			
			String root = request.getSession().getServletContext().getRealPath("");
			String savePath = root + File.separator+"upload"+File.separator+"temp"+File.separator;
			File fl = new File(savePath);
			if(!fl.exists()){
				fl.mkdirs();
			}
			if(flag){
				DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
				Calendar calendar = Calendar.getInstance();
				//以当前时间为文件名 格式如:20110903193036047     
                newName = df.format(calendar.getTime());    
                  
                Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(new String(extName.substring(1).getBytes(),"utf-8"));  
                ImageReader reader = it.next();   
                iis = ImageIO.createImageInputStream(multiFile.getInputStream());  
                reader.setInput(iis,true) ;  
                ImageReadParam param = reader.getDefaultReadParam();   
                Rectangle rect = new Rectangle(x, y, w, h);   
                param.setSourceRegion(rect);  
                System.out.println(extName.substring(1));  
               // BufferedImage bi = reader.read(0,param);   
                BufferedImage srcImage = reader.read(0);
                File tempfile = new File(savePath + "src" + extName); // 原图临时缓存地址
                ImageIO.write(srcImage, extName.substring(1), tempfile);
                File rectFile = new File(savePath + newName + extName); // 处理后图片缓存地址
                ImageHelper.cut(tempfile, rectFile, 280, 280, rect);
                //ImageIO.write(bi, extName.substring(1), rectFile); 
                int count = uploadPicToDB(rectFile); //写入到数据库
                if(count>0){
                    //File tempfile = new File(savePath);  
                    // 路径为文件且不为空则进行删除  
                    if (rectFile.isFile() && rectFile.exists()) {  
                    	rectFile.delete();  
                    }  
                    
                    if (tempfile.isFile() && tempfile.exists()) {  
                    	tempfile.delete();  
                    } 
                	result = 1;
                }
            }    
        }    
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("userCode", empNum);
		resultMap.put("result", result);
		resultMap.put("message", message);
		return new ModelAndView("/eip/changeMyPhoto.jsp",resultMap);
    }  



/**
	 * 展示图片
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("showMyPhoto")
	public void showMyPhoto(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		showMyPic(request, response);
	}

	
	public void showMyPic(HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		Locale locale = ContextUtil.getLocale();
		String localeLanguage = locale.getLanguage();
		System.out.println("当前的语言状态是:" + localeLanguage);
		String empNum = RequestUtil.getString(request, "empNum");
		List<UserProfile> uplist = userProfileService.getByEmpNum(empNum);
		if(uplist.size()>0){
			UserProfile up = uplist.get(0);
			if (up != null) {
				byte[] b = up.getPic();
				//System.out.println("图片大小--:"+b.length);
				if(b.length>0){
					response.setContentType("image/jpeg");
					response.setCharacterEncoding("UTF-8");
					OutputStream outs = null;
					InputStream  in = null;
					
					try {
						in  = new ByteArrayInputStream(b);
						outs = response.getOutputStream();
						byte[] buf = new byte[1024];
						int len = 0;
						while((len=in.read(buf, 0, 1024))!=-1){
							outs.write(buf, 0, len);
						}
					} finally {
						if (outs != null) {
							outs.close();
						}
						if (in != null) {
							in.close();
						}
					}
				}else{
					showDefaultPIC(request, response);
				}
			}
		}else{
			showDefaultPIC(request, response);
		}
	}
	
	public void showDefaultPIC(HttpServletRequest request, HttpServletResponse response) throws Exception{

		OutputStream outs = null;
		InputStream is = null;
		try {
			
			String root = request.getSession().getServletContext().getRealPath("");
			String savePath = root +
					File.separator+"styles"+
					File.separator+"eip"+
					File.separator+"images"+
					File.separator+"default_photo.png";
			File file = new File(savePath);
			is = new BufferedInputStream(new FileInputStream(file));
			long length = file.length();
			if(length>(1024*100)){
				throw new IOException("File is to large "+ file.getName());
			}
			byte[] buf = new byte[(int)length];
			int offset = 0;
			int numRead = 0;
			while(offset<buf.length && (numRead = is.read(buf, offset, buf.length-offset))>=0){
				offset += numRead;
			}
			
			if(offset < buf.length){
				throw new IOException("Could not completely read file " + file.getName());
			}
			outs = response.getOutputStream();
			outs.write(buf);
		} finally {
			if (outs != null) {
				outs.close();
			}
			if (is != null) {
				is.close();
			}
		}
	}

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spr" uri="http://www.springframework.org/tags"%>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>头像上传</title>

<link rel="stylesheet" type="text/css" href="${ctx}/js/jquery.imgareaselect-0.9.10/css/imgareaselect-default.css" />
<link rel="stylesheet" type="text/css" href="${ctx}/styles/eip/css/imagePreview.css" />
<script type="text/javascript" src="${ctx}/js/sf/eip/jquery.min.js"></script>
<script type="text/javascript" src="${ctx}/js/jquery.imgareaselect-0.9.10/scripts/jquery.imgareaselect.js"></script>
<script type="text/javascript" src="${ctx}/js/sf/eip/uploadPreview.js"></script>
<script type="text/javascript" src="${ctx}/js/sf/eip/uploadPreview.js"></script>
<script type="text/javascript">var popWin2;
</script>
<style type="text/css">
	body { font-family: 微软雅黑, 宋体, Arial, Helvetica, sans-serif; font-size: 12px; background: #f8f8f8}
</style>
</head>
<body>

<div class="demo">

	<div class="portrait_left">
		<form name="avatar_form" id="avatar_form"  action="${ctx}/eip/userProfile/uploadPic.ht" method="post"  enctype="multipart/form-data">
		<div id="picture" ><img id="avatar" name="avatar"  src="${ctx}/styles/eip/images/post_photo.png" class="tt"></div>
		<div><p font-color="grey"><spr:message code="eip.photo.supportPhoto"/></p></div>
   		 <input type="file" name="imgfile"  id="up"/>     
			<!--通过生成尺寸和旋转角度 后台获取尺寸和旋转角度再进行裁剪-->
			<input id="id_top" type="hidden" name="top" value="90">
			<input id="id_left" type="hidden" name="left" value="70">
			<input id="id_right" type="hidden" name="right" value="70">
			<input id="id_bottom" type="hidden" name="bottom" value="200">
			<input id="id_width" type="hidden" name="width" value="140">
			<input id="id_height" type="hidden" name="height" value="140">
		</form>
		<div class="setup_but"><button class="baseinf_but1" ><spr:message code="operator.upload"/></button></div>
	</div>
	<div class="portrait_right">
		<p class="portrait_right_txt"><spr:message code="eip.photo.comment"/></p>
		<div class="portrait_right_bottom">
			<div class="portrait1">
				<div id="img_big_preview" class="img_preview"><img id="avatar1" alt="头像预览" src=""  style="width:180px;height:180px" class="tt" /></div>
				<p><spr:message code="eip.photo.bigPhoto"/>,180×180</p>
			</div>
		</div>
			<div class="portrait2">
				<div id="img_small_preview" class="img_preview"><img id="avatar2" alt="预览ˆ" src="" style="width:50px;height:50px" class="tt"></div>
				<p><spr:message code="eip.photo.smallPhoto"/>, 50x50</p>
			</div>
		
	</div>
	
</div>



<br /><br />
<div style=" width:600px;margin:0 auto; text-align:center; font-size:12px;">
	<div id="loadingDiv"  style="display:none;top: 30%; left: 45%; position:fixed; background:#fff;filter:alpha(Opacity=80);-moz-opacity:0.5;opacity: 0.5;">
		<div ><img style="height:50px;width:50px;" src="${ctx}/js/ext/resources/themes/images/default/shared/large-loading.gif" /></div>
	</div>
<p></p>
</div>
<script type="text/javascript">
$(document).ready(function (){
	function adjust(el, selection) {
		var scaleX = $(el).width() / (selection.width || 1);
		var scaleY = $(el).height() / (selection.width || 1);
		//console.log(Math.round(scaleX*$('#avatar').width() ));
		$(el+' img').css({
			width: Math.round(scaleX*$('#avatar').width() ) + 'px',
			height: Math.round(scaleY*$('#avatar').height() ) + 'px',
			marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
			marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
		});
	}

	function preview(img, selection) {
		adjust('#img_big_preview', selection);
		adjust('#img_small_preview', selection);
	}
		

	$("#up").uploadPreview({ Img: "avatar", Width: 280, Height: 280 });
	$("#up").uploadPreview({ Img: "avatar1", Width: 180, Height: 180 });
	$("#up").uploadPreview({ Img: "avatar2", Width: 50, Height: 50 });
	
	$("#up").change(function(){
		//style="width:360px;height:360px;margin-left:-90px;margin-top:-90px;"
		$("#avatar1").attr("style","width:360px;height:360px;margin-left:-90px;margin-top:-90px;");
		//style="width: 100px; height: 100px; margin-left: -25px; margin-top: -25px;"
		$("#avatar2").attr("style","width: 100px; height: 100px; margin-left: -25px; margin-top: -25px;");
		$('img#avatar').imgAreaSelect({
			aspectRatio: "1:1",
			x1: 70,
			y1:70,
			x2: 210,
			y2: 210,
			minWidth: 50, 
			minHeight: 50,
			maxWidth: 280, 
			maxHeight: 280,
			handle:true,
			onSelectEnd:function(img, selection) {
				$('#id_top').val(selection.y1);
				$('#id_left').val(selection.x1);
				$('#id_right').val(selection.x2);
				$('#id_bottom').val(selection.y2);
				$('#id_width').val(selection.width);
				$('#id_height').val(selection.height);
			},
			onSelectChange: preview
		});
	});
	
	var showIfm = parent.document.all.showIfm
	$maskTop = $(showIfm).parent('#maskTop');
	
	$popWinClose = $maskTop.find('#popWinClose');
	
	$myPhoto = $maskTop.parents().find("#post_main").find("#myPhoto>img");
	var url = "${ctx}/eip/userProfile/showMyPhoto.ht?empNum=${userCode}"+"×tamp=" + new Date().getTime();
	$myPhoto.attr("src",url);
	
	$("#avatar1").attr("src",url);
	$("#avatar2").attr("src",url);
	/*
	var url = $myPhoto.attr("src");
	var url1 ="${ctx}/eip/userProfile/showMyPhoto.ht?empNum=${userCode}";
	var url2 ="${ctx}/eip/userProfile/showPic.ht?empNum=${userCode}";
	
	if(url==url1){
		url = url2+"×tamp=" + new Date().getTime();
	}else if(url == url2){
		url = url1+"×tamp=" + new Date().getTime();
	}
	
	//$maskTop.parents().find();
	
	*/
	
	var result = '${result}';
	if(result == 0 || result == '0'){
		var message = '${message}';
			if(message =="toolarge"){
				alert("<spr:message code='eip.photo.info.msg'/>");
			}else if(message =="invalidformat"){
				alert("<spr:message code='eip.photo.unsupportFmt'/>");
			}
			var flag = false;
			$("#up").change(function(){
				flag = true;
			});
			$(".baseinf_but1").bind('click',function(){
				var upval = $("#up").val();
					if(upval.length==0){
						alert("<spr:message code='eip.photo.null'/>");
						return false;
					}else{
						
						if($('#id_width').val()<=0||$('#id_height').val()<=0){
							alert("<spr:message code='eip.photo.zero'/>");
							return false;
						}else{
							/*
							var img = $("#avatar").get(0);
							
							var wh = getImgNaturalDimensions(img);
							//alert(wh[0] +"----"+$('#id_width').val());
							//alert(wh[1] + "---" + $('#id_height').val());
							if(wh[0] <= 135 || wh[1] <= 135){
								alert("图片尺寸太小,请更换新的图片");
								return;
							}else if(wh[0]>500 || wh[1]>500){
								alert("图片尺寸太大,请更换新的图片");
								return;
							}*/
							
							$('#avatar_form').submit();
							
							$('#loadingDiv').show();
							$(".setup_but").html("<span><font color='red'><h3><spr:message code='eip.photo.uploading'/></h3></font></span>");
							//$popWinClose.trigger('click');
						}
					}
			});
			
	}
	else{
		//window.location.herf=;
		//$maskTop.attr("flag",true);
		$("#avatar").attr("src",url);
		$(".setup_but").html("<span><font color='red'><h3><spr:message code='eip.photo.uploading'/></h3></font></span>");
		alert("<spr:message code='eip.photo.uploadSuccess'/>");
		
		$popWinClose.click();
		//$(".baseinf_but1").unbind('click');
	}
	
}); 

function uploadavatar(){
	$maskTop.attr("flag",true);
	$(".baseinf_but1").disabled();
	$('#avatar_form').submit();
	//$(this).disabled();
	//$(showIfm).parent
}


function getImgNaturalDimensions(img, callback) {
	
    var nWidth=0, nHeight=0;
    if (img.naturalWidth) { // 现代浏览器
        nWidth = img.naturalWidth;
        nHeight = img.naturalHeight;
    } else { // IE6/7/8
        var image = new Image();
        image.src = img.src;
        nWidth = image.width;
        nHeight = image.width;
        /*
        image.onload = function() {
        	//alert(image.width);
        	//alert(image.width);
            callback(image.width, image.height);
            
        }
        */
    }
    //alert(nWidth);
	//alert(nHeight);
    return [nWidth,nHeight];
    //return {'nWidth':nWidth, 'nHeight':nHeight};
}




</script>

</body>
</html>

/*
*名称:图片上传本地预览插件 v1.1
*作者:周祥
*时间:2013年11月26日
*介绍:基于JQUERY扩展,图片上传预览插件 目前兼容浏览器(IE 谷歌 火狐) 不支持safari
*插件网站:http://keleyi.com/keleyi/phtml/image/16.htm
*参数说明: Img:图片ID;Width:预览宽度;Height:预览高度;ImgType:支持文件类型;Callback:选择文件显示图片后回调方法;
*使用方法: 
<div>
<img id="ImgPr" width="120" height="120" /></div>
<input type="file" id="up" />
把需要进行预览的IMG标签外 套一个DIV 然后给上传控件ID给予uploadPreview事件
$("#up").uploadPreview({ Img: "ImgPr", Width: 120, Height: 120, ImgType: ["gif", "jpeg", "jpg", "bmp", "png"], Callback: function () { }});
*/
jQuery.fn.extend({
    uploadPreview: function (opts) {
        var _self = this,
            _this = $(this);
        opts = jQuery.extend({
            Img: "ImgPr",
            Width: 100,
            Height: 100,
            ImgType: ["gif", "jpeg", "jpg", "bmp", "png"],
            Callback: function () {}
        }, opts || {});
        _self.getObjectURL = function (file) {
            var url = null;
            if (window.createObjectURL != undefined) {
                url = window.createObjectURL(file)
            } else if (window.URL != undefined) {
                url = window.URL.createObjectURL(file)
            } else if (window.webkitURL != undefined) {
                url = window.webkitURL.createObjectURL(file)
            }
            return url
        };
        _this.change(function () {
            if (this.value) {
				/*
                if (!RegExp("\.(" + opts.ImgType.join("|") + ")$", "i").test(this.value.toLowerCase())) {
                    alert("选择文件错误,图片类型必须是" + opts.ImgType.join(",") + "中的一种");
                    this.value = "";
                    return false
                }
                */
                if ($.browser.msie) {
                    try {
                        //$("#" + opts.Img).attr('src', _self.getObjectURL(this.files[0]))
						
						//$("#up").val().replace(/\\/gi,'/');
						
                        $(".tt").attr("src",$("#up").val());
						//alert("file:///"+$("#up").val());

                    } catch (e) {
                        var src = "";
                        var obj = $("#" + opts.Img);
                        var div = obj.parent("div")[0];
                        _self.select();
                        if (top != self) {
                            window.parent.document.body.focus()
                        } else {
                            _self.blur()
                        }
                        src = document.selection.createRange().text;
                        document.selection.empty();
                        obj.hide();
                        obj.parent("div").css({
                            'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)',
                            'width': opts.Width + 'px',
                            'height': opts.Height + 'px'
                        });
                        div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src
                    }
                } else {
                    $("#" + opts.Img).attr('src', _self.getObjectURL(this.files[0]))
                }
                opts.Callback()
            }
        })
    }
});

package com.sf.eip.util;


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import javax.imageio.ImageIO;

public class ImageHelper { 

	 /**
	  * @Description: 将srcImageFile裁剪后生成destImageFile
	  * @param srcImageFile  原始图
	  * @param destImageFile  目标图
	  * @param width          原始图预处理后width
	  * @param height         原始图预处理后height
	  * @param rect           目标图输出的格式(rect.x, rect.y, rect.width, rect.height)
	  * @throws IOException
	  * @author Sun Yanjun
	  */
	public static void cut(String srcImageFile, String destImageFile,
			int width, int height, Rectangle rect) throws IOException {
		Image image = ImageIO.read(new File(srcImageFile));
		BufferedImage bImage = makeThumbnail(image, width, height);

		// 把原始图片输出
		ImageIO.write(bImage, "jpg", new File("img/src2.jpg"));

		saveSubImage(bImage, rect, new File(destImageFile));
	}
 
	 /**
	  * @Description: 将srcImageFile裁剪后生成destImageFile
	  * @param srcImageFile  原始图
	  * @param destImageFile  目标图
	  * @param width          原始图预处理后width
	  * @param height         原始图预处理后height
	  * @param rect           目标图输出的格式(rect.x, rect.y, rect.width, rect.height)
	  * @throws IOException
	  * @author Sun Yanjun
	  */
	public static void cut(File srcImageFile, File destImageFile, int width,
			int height, Rectangle rect) throws IOException {
		Image image = ImageIO.read(srcImageFile);
		BufferedImage bImage = makeThumbnail(image, width, height);

		saveSubImage(bImage, rect, destImageFile);
	}
 
	 /**
	  * @Description: 对原始图片根据(x, y, width, height) = (0, 0, width, height)进行缩放,生成BufferImage
	  * @param img
	  * @param width 预处理后图片的宽度
	  * @param height 预处理后图片高度
	  * @return
	  * @author Sun Yanjun
	  * @throws IOException
	  */
	private static BufferedImage makeThumbnail(Image img, int width, int height)
			throws IOException {
		BufferedImage tag = new BufferedImage(width, height, 1);
		Graphics g = tag.getGraphics();
		g.drawImage(img.getScaledInstance(width, height, 4), 0, 0, null);

		g.dispose();
		return tag;
	}

	 /**
	  * @Description: 对BufferImage按照(x, y, width, height) = (subImageBounds.x, subImageBounds.y, subImageBounds.width, subImageBounds.height)进行裁剪
	  *               如果subImageBounds范围过大,则用空白填充周围的区域。
	  *              
	  * @param image
	  * @param subImageBounds
	  * @param destImageFile
	  * @throws IOException
	  * @author Sun Yanjun
	  */
	private static void saveSubImage(BufferedImage image,
			Rectangle subImageBounds, File destImageFile) throws IOException {
		String fileName = destImageFile.getName();
		String formatName = fileName.substring(fileName.lastIndexOf('.') + 1);
		BufferedImage subImage = new BufferedImage(subImageBounds.width,
				subImageBounds.height, 1);
		Graphics g = subImage.getGraphics();

		if ((subImageBounds.width > image.getWidth())
				|| (subImageBounds.height > image.getHeight())) {
			int top = subImageBounds.x;
			int left = subImageBounds.y;
			if (image.getWidth() < subImageBounds.width)
				left = (subImageBounds.width - image.getWidth()) / 2;
			if (image.getHeight() < subImageBounds.height)
				top = (subImageBounds.height - image.getHeight()) / 2;
			g.setColor(Color.white);
			g.fillRect(0, 0, subImageBounds.width, subImageBounds.height);
			g.drawImage(image, left, top, null);
			ImageIO.write(image, formatName, destImageFile);
		} else {
			g.drawImage(image.getSubimage(subImageBounds.y, subImageBounds.x,
					subImageBounds.width, subImageBounds.height), 0, 0, null);
		}
		g.dispose();
		ImageIO.write(subImage, formatName, destImageFile);
	}
}
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值