/** * 从网上摘抄的。 * 返回包含所有当前已注册 ImageReader 的 Iterator,这些 ImageReader 声称能够解码指定格式。 * 参数:formatName - 包含非正式格式名称 .(例如 "jpeg" 或 "tiff")等 。 * * @param postFix * 文件的后缀名 * @author 刘各欢 * @return */ public Iterator<ImageReader> getImageReadersByFormatName(String postFix) { switch (postFix) { case "jpg": return ImageIO.getImageReadersByFormatName("jpg"); case "jpeg": return ImageIO.getImageReadersByFormatName("jpeg"); case "gif": return ImageIO.getImageReadersByFormatName("gif"); case "bmp": return ImageIO.getImageReadersByFormatName("bmp"); case "png": return ImageIO.getImageReadersByFormatName("png"); default: return ImageIO.getImageReadersByFormatName("jpg"); } } /** * * fileCut:传入一个图片文件,返回一个剪切过的文件流 * * @author 刘各欢 * @param in * @param x * @param y * @param width * @param height * @param showHeight * @param showWidth * @throws IOException * @since Ver 1.1 */ public void fileCut(String postFix,InputStream in,FileOutputStream out,int x,int y,int width,int height,int showHeight,int showWidth) throws IOException{ //FileInputStream is = null; ImageInputStream iis = null; try { // 读取图片文件 //is = new FileInputStream(in); // 获取文件的后缀名 System.out.println("图片格式为:" + postFix); /* * 返回包含所有当前已注册 ImageReader 的 Iterator,这些 ImageReader 声称能够解码指定格式。 * 参数:formatName - 包含非正式格式名称 .(例如 "jpeg" 或 "tiff")等 。 */ Iterator<ImageReader> it = getImageReadersByFormatName(postFix); ImageReader reader = it.next(); // 获取图片流 iis = ImageIO.createImageInputStream(in); /* * <p>iis:读取源.true:只向前搜索 </p>.将它标记为 ‘只向前搜索’。 * 此设置意味着包含在输入源中的图像将只按顺序读取,可能允许 reader 避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。 */ reader.setInput(iis, true); int realWidth = reader.getWidth(0); int realHeight = reader.getHeight(0); double xBilv = showWidth/(double)realWidth; double yBilv = showHeight/(double)realHeight; BigDecimal realX = new BigDecimal(x/xBilv); BigDecimal realY = new BigDecimal(y/yBilv); BigDecimal caijianWidth = new BigDecimal(width/xBilv); BigDecimal caijianHeight = new BigDecimal(height/yBilv); /* * <p>描述如何对流进行解码的类<p>.用于指定如何在输入时从 Java Image I/O * 框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件 将从其 ImageReader 实现的 * getDefaultReadParam 方法中返回 ImageReadParam 的实例。 */ ImageReadParam param = reader.getDefaultReadParam(); /* * 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域,通过 Rectangle 对象 * 的左上顶点的坐标(x,y)、宽度和高度可以定义这个区域。 */ Rectangle rect = new Rectangle(realX.intValue(), realY.intValue(), caijianWidth.intValue(), caijianHeight.intValue()); // 提供一个 BufferedImage,将其用作解码像素数据的目标。 param.setSourceRegion(rect); /* * 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象,并将 它作为一个完整的 * BufferedImage 返回。 */ BufferedImage bi = reader.read(0, param); /* * 缩放图片 */ Image imageSmall = bi.getScaledInstance(100, 100, Image.SCALE_DEFAULT); BufferedImage small = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); Graphics g = small.getGraphics(); g.drawImage(imageSmall, 0, 0, null); // 绘制缩小后的图 将Image绘制到BufferedImage中 g.dispose(); // 保存新图片 //ImageIO.write(bi, postFix, new File("3_" + new Date().getTime() + "." + postFix)); ImageIO.write(small, postFix, out); } finally { if (in != null) in.close(); if (iis != null) iis.close(); if (out != null) out.close(); } }
主调用方法:
/** * * saveOrUpdate:修改个人信息 * * @author 王岩 * @param id * @param username * @param email * @param phonenum * @param address * @param sex * @param request * @return * @throws NoSuchAlgorithmException * @since Ver 1.1 */ @RequestMapping(value = "/update.do") public String saveOrUpdate(String username, MultipartFile pic, String img_x,String img_y,String img_w,String img_h, HttpServletRequest request) throws NoSuchAlgorithmException //String email,Date date, Integer phonenum, String address, String sex, { HttpSession session=request.getSession(); User users = (User)session.getAttribute("curruser"); String id=users.getId(); String pathString = CommonInfo.realDir + CommonInfo.productImageRealDir; User user = null; if (StringUtils.isNotBlank(id)) { user = userService.get(id); } user.setUsername(username); //user.setEmail(email); //user.setPhonenum(phonenum); //user.setAddress(address); //user.setSex(sex); //user.setDate(date); /************************************************** * * * */ /************************************************** * * * */ if (pic.getSize() > 0) { user.setImage(pathString + pic.getOriginalFilename()); File file = new File(pathString); if (!file.exists() && !file.isDirectory()) { file.mkdirs(); } try { FileOutputStream fout = new FileOutputStream("D:\\" + pic.getOriginalFilename()); int x = new BigDecimal(img_x).intValue(); int y = new BigDecimal(img_y).intValue(); int w = new BigDecimal(img_w).intValue(); int h = new BigDecimal(img_h).intValue(); String ext=pic.getOriginalFilename().substring(pic.getOriginalFilename().lastIndexOf(".")+1,pic.getOriginalFilename().length()); this.fileCut(ext.toLowerCase(),pic.getInputStream(),fout,x,y,w,h,200,200); if(fout!=null) fout.close(); //pic.transferTo(new File()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } String path = user.getImage(); request.getSession().setAttribute("path", path); userService.saveOrUpdate(user); return "redirect:personal.do"; }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <html> <head> <meta name="renderer" content="webkit"> <meta charset="utf-8"> <title>个人信息</title> <%@ include file="/WEB-INF/jsp/commons/includes.jsp"%> <script src="${contextPath}/scripts/jquery.jcrop.min.js"></script> <link rel="stylesheet" href="${contextPath}/css/jquery.jcrop.css" /> <script type="text/javascript"> function caijian(){ // Create variables (in this scope) to hold the API and image size var jcrop_api, boundx, boundy; $('#p_img').Jcrop({ onChange: updatePreview, onSelect: updatePreview, aspectRatio: 1, setSelect: [0,0,150,150] },function(){ // Use the API to get the real image size var bounds = this.getBounds(); boundx = bounds[0]; boundy = bounds[1]; console.log(1111); console.log(bounds); // Store the API in the jcrop_api variable jcrop_api = this; }); function updatePreview(c) { if (parseInt(c.w) > 0) { var bilv = $('#p_img').width()/ console.log(c); $("#img_x").val(c.x); $("#img_y").val(c.y); $("#img_w").val(c.w); $("#img_h").val(c.h); var rx = 100 / c.w; var ry = 100 / c.h; $('#p_img_preview').css({ width: Math.round(rx * boundx) + 'px', height: Math.round(ry * boundy) + 'px', marginLeft: '-' + Math.round(rx * c.x) + 'px', marginTop: '-' + Math.round(ry * c.y) + 'px' }); } }; } //建立一個可存取到該file的url function getObjectURL(file) { var url = null ; if (window.createObjectURL!=undefined) { // basic url = window.createObjectURL(file) ; } else if (window.URL!=undefined) { // mozilla(firefox) url = window.URL.createObjectURL(file) ; } else if (window.webkitURL!=undefined) { // webkit or chrome url = window.webkitURL.createObjectURL(file) ; } return url ; } $(document).ready( function() { $('#p_img_preview').css({ width: 150 + 'px', height: 150 + 'px'}); $("#pic").change(function(){ console.log(this.files[0]); var objUrl = getObjectURL(this.files[0]) ; console.log("objUrl = "+objUrl) ; if (objUrl) { $("#p_img").attr("src", objUrl+"") ; $("#p_img_preview").attr("src", objUrl+"") ; caijian(); $(".jcrop-holder img").attr("src",objUrl+""); } }) ; } ); $(function() { $("input[type=radio][name=sex][value=${user.sex}]").attr("checked", "checked"); }); jQuery(function($) { $("#address").keydown(function(e) { if (e.keyCode == 13) { loginSubmit(); } }); }); </script> </head> <body> <%@ include file="/WEB-INF/jsp/commons/header.jsp"%> <%@ include file="/WEB-INF/jsp/commons/menu.jsp"%> <div class="mainContainer sixteen container"> <!--Header Block--> <!--Content Block--> <section class="content-wrapper"> <div class="content-container container"> <%@ include file="/WEB-INF/jsp/commons/left.jsp"%> <div class="col-main"> <form id="reg-form" method="post" action="${contextPath}/update.do" enctype="multipart/form-data" > <!-- 修改个人信息 --> <div class="main"> <h1 class="page-title">完善个人信息</h1> <div class="fieldset"> <input type="hidden" name="id" value="${curruser.id}" /> <h2 class="legend">个人信息</h2> <div> <ul class="form-list" style="float: left"> <li> <div class="input-box"> <span>用户名</span> :${user.username} <input type="hidden" name="username" value="${user.username}"> </div> </li> <li> <div> <br> <span>性别<em>*</em></span> <input type="radio" name="sex" value="0" />男 <input type="radio" name="sex" value="1" />女 <input type="radio" name="sex" value="2" />保密 </div> </li> <li> <div> <br><span>出生年月<em>*</em></span><br> <%-- <input type="date" id="date" value="${user.date}" name="date"/> --%> <input type="date" name="date"> </div> </li> <li> <div class="input-box"> <br> <span>手机号<em>*</em></span> <br> <input type="text" title="手机号" value="${user.phonenum}" name="phonenum" required="true" id="phonenum" class="easyui-numberbox" size="8" maxlength="11" /> </div> <div class="clear"></div> </li> <li> <div class="input-box"> <br> <span>邮箱<em>*</em></span> <br> <input type="text" title="邮箱" value="${user.email}" name="email" id="email" required="true" class="easyui-validatebox" missingMessage="邮件必须填写" validType="email" invalidMessage="请填写正确的邮件格式" /> </div> </li> <li> <div class="input-box"> <br> <span>所在地<em>*</em></span> <br> <input type="text" required="true" class="easyui-validatebox" title="所在地" value="${user.address}" name="address" id="address" /> </div> </li> </ul> <ul style="float: right"> <li> <div style="width:200px;"> <%-- src="${contextPath}/images/honglou1.png" --%> <img id="p_img" alt="原始" style="width:200px;height:200px;" src="${contextPath}/images/honglou1.png" /> <div style="width:80px;height:80px;overflow:hidden;"> <img id="p_img_preview" class="jcrop-preview" alt="预览图片" src="${contextPath}/images/honglou1.png" /> </div> </div> <div> <br> <span>头像<em>*</em></span> <input type="file" id="pic" name="pic" class="easyui-filebox"> <input type="hidden" id="img_x" name="img_x" /> <input type="hidden" id="img_y" name="img_y" /> <input type="hidden" id="img_w" name="img_w" /> <input type="hidden" id="img_h" name="img_h" /> </div> </li> </ul> </div> <br> <div class="buttons-set" style="margin-top: 350px"> <p class="required">* 必填项</p> <!-- class="orange-btn" --> <input type="submit" title="Submit" value="提交" class="orange-btn" style="margin-bottom: 20px;"> <div class="clear"></div> </div> </div> </div> </form> </div> <%-- <div class="clearfix"></div> <%@ include file="/WEB-INF/jsp/commons/main.jsp"%> --%> </div> </section> </div> <!--Footer Block--> <%@ include file="/WEB-INF/jsp/commons/footer.jsp"%> </body> </html>
版权声明:本文为博主原创文章,未经博主允许不得转载。