java实现上传图片进行切割

  1. 云栖社区>
  2. 博客>
  3. 正文

java实现上传图片进行切割

benjaminwhx 2016-05-19 14:42:25 浏览1443
展开阅读全文

 为什么我要进行上传的图片进行切割呢,我这个项目的图片是部门logo,每个部门都可以选择不同的logo,但是要应对浏览器的兼容以及拉伸,我选择了把一张图片切成左、中、右和剩下的部分,因为左边和中变可能会有图案或者字所以不能拉伸,拉伸的只是右边的部分,剩下的部分自适应就可以了。所以用了javax的ImageReader来操作。最后以blob类型保存数据库中。

首先要在form表单里面写上enctype="multipart/form-data"

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <form method="post" id="mainForm" action="${ctx }/admin/department!save.action" enctype="multipart/form-data">  

下面在表单中写上上传组件

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <tr>  
  2.                 <td style="width: 100px;">  
  3.                     <strong>上传Logo:</strong>  
  4.                     <input type="hidden" name="suffix" id="suffix" value="${depart.departmentLogo.suffix }"/>  
  5.                 </td>  
  6.                 <td style="width: 225px;">  
  7.                     <input type="file" name="logoFile" id="logoFile" onchange="checkFile();"/>  
  8.                 </td>  
  9.             </tr>  
  10.             <tr>  
  11.                 <td style="width: 100px;"></td>  
  12.                 <td style="width: 225px;">  
  13.                     <span class="red">(图片格式:jpg,jpeg,bmp,gif,png;</span><br/>  
  14.                     <span class="red">推荐大小:1120×80像素)</span>  
  15.                 </td>  
  16.             </tr>  

图片检查的checkFile()方法用于检查图片是否以规定格式结尾以及是否没有选择

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. function checkFile(){  
  2.           
  3.         var value = $("#logoFile").val();  
  4.         if(!value){  
  5.             alert("请选择您要上传的图片!");  
  6.             return false;  
  7.         }else{  
  8.             if(value.lastIndexOf(".jpg") != -1){  
  9.                 $("#suffix").val("jpg");  
  10.                 return true;  
  11.             }else if(value.lastIndexOf(".jpeg") != -1){  
  12.                 $("#suffix").val("jpeg");  
  13.                 return true;  
  14.             }else if(value.lastIndexOf(".gif") != -1){  
  15.                 $("#suffix").val("gif");  
  16.                 return true;  
  17.             }else if(value.lastIndexOf(".bmp") != -1){  
  18.                 $("#suffix").val("bmp");  
  19.                 return true;  
  20.             }else if(value.lastIndexOf(".png") != -1){  
  21.                 $("#suffix").val("png");  
  22.                 return true;  
  23.             }else{  
  24.                 alert("对不起,您上传文件格式有误,请选择指定格式的图片文件上传");  
  25.                 return false;  
  26.             }  
  27.         }  
  28.           
  29.     }  

下面就是进行后台的save操作了。

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. public String save() throws Exception {  
  2.         HttpServletRequest request = ServletActionContext.getRequest() ;  
  3.         String departId = request.getParameter("id") ;  
  4.         String departName = request.getParameter("name") ;  
  5.         String companyId = request.getParameter("companyId") ;  
  6.         //图片后缀  
  7.         String suffix = request.getParameter("suffix");  
  8.         List<Menu> listMenu = new ArrayList<Menu>() ;  
  9.         Company company = new Company() ;  
  10.         company.setId(Long.valueOf(companyId)) ;  
  11.         if(this.logoFile != null && departName != null && companyId != null && suffix != null){  
  12.             //获取解析图片的ImageReader  
  13.             Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName(suffix);  
  14.             ImageReader imageReader = imageReaders.next();  
  15.             //把图片以字节流的形式传入  
  16.             InputStream logoStream = new BufferedInputStream(new FileInputStream(this.logoFile));  
  17.             //转为图片输入流  
  18.             ImageInputStream imageInputStream = ImageIO.createImageInputStream(logoStream);  
  19.             imageReader.setInput(imageInputStream, true);  
  20.             int imageWidth = imageReader.getWidth(0);  
  21.             //固定高度80  
  22.             int imageHeight = 80;  
  23.             //设置左中右和剩下的宽度  
  24.             int leftWidth = imageWidth / 2;  
  25.             int middleWidth = (imageWidth - leftWidth) / 3;  
  26.             int rightWidth = 5;  
  27.             int retainWidth = imageWidth - leftWidth -middleWidth - 5;  
  28.               
  29.             ImageReadParam readParam = imageReader.getDefaultReadParam();  
  30.             BufferedImage bImage = null;  
  31.             //裁剪左半部分  
  32.             //根据宽和高获得矩形  
  33.             Rectangle leftImageRectangle = new Rectangle(0, 0, leftWidth, imageHeight);  
  34.             readParam.setSourceRegion(leftImageRectangle);  
  35.             bImage = imageReader.read(0, readParam);   
  36.             //字节数组输出流  
  37.             ByteArrayOutputStream leftByteArrayOutputStream = new ByteArrayOutputStream();  
  38.             ImageIO.write(bImage, suffix, leftByteArrayOutputStream);  
  39.             //获得字节数组  
  40.             byte[] leftImageData = leftByteArrayOutputStream.toByteArray();  
  41.             leftByteArrayOutputStream.close();  
  42.             //Hibernate创建一个blob类型  
  43.             Blob leftBlob = Hibernate.createBlob(leftImageData, this.departmentManager.getSession());  
  44.               
  45.             //裁剪中部部分  
  46.             Rectangle middleImageRectangle = new Rectangle(leftWidth, 0 , middleWidth, imageHeight);  
  47.             readParam.setSourceRegion(middleImageRectangle);  
  48.             bImage = imageReader.read(0, readParam);  
  49.               
  50.             ByteArrayOutputStream middleArrayOutputStream = new ByteArrayOutputStream();  
  51.             ImageIO.write(bImage, suffix, middleArrayOutputStream);  
  52.             byte[] middleImageData = middleArrayOutputStream.toByteArray();  
  53.             middleArrayOutputStream.close();  
  54.             Blob middleBlob = Hibernate.createBlob(middleImageData, this.departmentManager.getSession());  
  55.               
  56.             //裁剪右半部分  
  57.             Rectangle rightImageRectangle = new Rectangle(leftWidth + middleWidth, 0, rightWidth, imageHeight);  
  58.             readParam.setSourceRegion(rightImageRectangle);  
  59.             bImage = imageReader.read(0, readParam);  
  60.               
  61.             ByteArrayOutputStream rightArrayOutputStream = new ByteArrayOutputStream();  
  62.             ImageIO.write(bImage, suffix, rightArrayOutputStream);  
  63.             byte[] rightImageData = rightArrayOutputStream.toByteArray();  
  64.             rightArrayOutputStream.close();  
  65.             Blob rightBlob = Hibernate.createBlob(rightImageData, this.departmentManager.getSession());  
  66.               
  67.             //保留部分  
  68.             Rectangle retainRectangle = new Rectangle(leftWidth + middleWidth + rightWidth, 0, retainWidth, imageHeight);  
  69.             readParam.setSourceRegion(retainRectangle);  
  70.             bImage = imageReader.read(0, readParam);  
  71.               
  72.             ByteArrayOutputStream retainArrayOutputStream = new ByteArrayOutputStream();  
  73.             ImageIO.write(bImage, suffix, retainArrayOutputStream);  
  74.             byte[] retainImageData = retainArrayOutputStream.toByteArray();  
  75.             retainArrayOutputStream.close();  
  76.             Blob retainBlob = Hibernate.createBlob(retainImageData, this.departmentManager.getSession());  
  77.               
  78.             if(!departId.equals("") && departId!=null){  
  79.                 Department d = this.departmentManager.findById(Long.valueOf(departId)) ;  
  80.                 if(this.checkedAuthIds != null){  
  81.                     for(int i=0;i<checkedAuthIds.size();i++){  
  82.                         Menu menu = new Menu() ;  
  83.                         menu.setId(checkedAuthIds.get(i)) ;  
  84.                         listMenu.add(menu) ;  
  85.                     }  
  86.                     d.setMenus(listMenu) ;  
  87.                 }  
  88.                 d.getDepartmentLogo().setLeftPartImage(leftBlob);  
  89.                 d.getDepartmentLogo().setMiddlePartImage(middleBlob);  
  90.                 d.getDepartmentLogo().setRightPartImage(rightBlob);  
  91.                 d.getDepartmentLogo().setRetainPartImage(retainBlob);  
  92.                 d.getDepartmentLogo().setCreateTime(new Date());  
  93.                 d.getDepartmentLogo().setSuffix(suffix);  
  94.                 d.setName(departName) ;  
  95.                 d.setParentId(0L) ;  
  96.                 d.setNodeType(1) ;  
  97.                 d.setGrade(1) ;  
  98.                 d.setCompany(company) ;  
  99.                 this.departmentManager.save(d) ;  
  100.             }else{  
  101.                 Integer parentNodeType = 0 ;  
  102.                 Department dd = new Department() ;  
  103.                 if(this.checkedAuthIds!=null && this.checkedAuthIds.size() != 0){  
  104.                     for(int i=0;i<checkedAuthIds.size();i++){  
  105.                         Menu menu = new Menu() ;  
  106.                         menu.setId(checkedAuthIds.get(i)) ;  
  107.                         listMenu.add(menu) ;  
  108.                     }  
  109.                     dd.setMenus(listMenu) ;  
  110.                 }else{  
  111.                     dd.setMenus(null) ;  
  112.                 }  
  113.                 DepartmentLogo departmentLogo = new DepartmentLogo() ;  
  114.                 departmentLogo.setCreateTime(new Date());  
  115.                 departmentLogo.setLeftPartImage(leftBlob);  
  116.                 departmentLogo.setMiddlePartImage(middleBlob);  
  117.                 departmentLogo.setRightPartImage(rightBlob);  
  118.                 departmentLogo.setRetainPartImage(retainBlob);  
  119.                 departmentLogo.setSuffix(suffix);  
  120.                 dd.setDepartmentLogo(departmentLogo);  
  121.                 dd.getDepartmentLogo().setDepartment(dd);  
  122.                 dd.setId(this.departmentManager.findMaxId()+1) ;  
  123.                 dd.setName(departName) ;  
  124.                 dd.setParentId(0L) ;  
  125.                 dd.setNodeType(1) ;  
  126.                 dd.setGrade(1) ;  
  127.                 dd.setOrderType(0) ;  
  128.                 dd.setCompany(company) ;  
  129.                 dd.setFlag(0) ;  
  130.                 this.departmentManager.save(dd) ;  
  131.             }  
  132.         }  
  133.           
  134.           
  135.         return "reload";  
  136.     }  

下面就是显示了,我是用的qui,所以在top.jsp上面的css中进行动态显示

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <style type="text/css">  
  2.         .welcome-hide{width: 210px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;}  
  3.         #leftLogo{background: url(${ctx }/admin/department-logo!showLogo.action?position=left) no-repeat;width: ${leftWidth}px;height: 80px;}  
  4.         #middleLogo{background: url(${ctx }/admin/department-logo!showLogo.action?position=middle) no-repeat;width: ${middleWidth}px;height: 80px;}  
  5.         #rightLogo,#topTableStyle{background: url(${ctx }/admin/department-logo!showLogo.action?position=right) repeat-x;height: 80px;}  
  6.         #retainLogo{background: url(${ctx }/admin/department-logo!showLogo.action?position=retain) no-repeat;width: ${retainWidth}px;height: 80px;}  
  7.     </style>  
department-logo!showLogo.action中的showLogo方法就是加载图片的方法

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. public String showLogo() {  
  2.           
  3.         HttpServletRequest request = ServletActionContext.getRequest();  
  4.         LoginUser loginUser = (LoginUser)((SecurityContext)request.getSession().  
  5.                 getAttribute("SPRING_SECURITY_CONTEXT")).getAuthentication().getPrincipal();  
  6.         List<DepartmentLogo> logos = this.logoManager.findAll();  
  7.         for (DepartmentLogo departmentLogo : logos) {  
  8.             if (loginUser.getUser().getDepartment().getId().equals(departmentLogo.getDepartment().getId())) {  
  9.                 String param = request.getParameter("position");  
  10.                 Blob blob = null;  
  11.                 if (param != null) {  
  12.                     try {  
  13.                         if (param.equals("left")) {  
  14.                             blob = departmentLogo.getLeftPartImage();  
  15.                             imageLogo = blob.getBinaryStream();  
  16.                             return "showLogo";  
  17.                         }else if (param.equals("middle")) {  
  18.                             blob = departmentLogo.getMiddlePartImage();  
  19.                             imageLogo = blob.getBinaryStream();  
  20.                             return "showLogo";  
  21.                         }else if (param.equals("right")) {  
  22.                             blob = departmentLogo.getRightPartImage();  
  23.                             imageLogo = blob.getBinaryStream();  
  24.                             return "showLogo";  
  25.                         }else if (param.equals("retain")) {  
  26.                             blob = departmentLogo.getRetainPartImage();  
  27.                             imageLogo = blob.getBinaryStream();  
  28.                             return "showLogo";  
  29.                         }  
  30.                     } catch (Exception e) {  
  31.                         e.printStackTrace();  
  32.                     }  
  33.                 }  
  34.             }  
  35.         }  
  36.           
  37.         return null;  
  38.     }  

当然返回的地址应该选择struts2中的type="stream"

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. @Results({  
  2.     @Result(name = "showLogo"type = "stream"params = {"contentType", "image/jpeg,"  
  3.             + "image/bmp,image/png,image/gif,image/jpeg",   
  4.             "inputName", "imageLogo", "bufferSize", "4096"})  
  5. })  

那么top.jsp中的width是怎么得到的呢?

实在加载菜单的时候得到的,下面是menu中的方法

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. HttpServletRequest request = ServletActionContext.getRequest();  
  2.         List<DepartmentLogo> logos = this.logoManager.findAll();  
  3.         for (DepartmentLogo departmentLogo : logos) {  
  4.             if (user.getDepartment().getId().equals(departmentLogo.getDepartment().getId())) {  
  5.                 request.setAttribute("leftWidth", ImageIO.read(departmentLogo.  
  6.                         getLeftPartImage().getBinaryStream()).getWidth());  
  7.                 request.setAttribute("middleWidth", ImageIO.read(departmentLogo.  
  8.                         getMiddlePartImage().getBinaryStream()).getWidth());  
  9.                 request.setAttribute("retainWidth", ImageIO.read(departmentLogo.  
  10.                         getRetainPartImage().getBinaryStream()).getWidth());  
  11.                 break;  
  12.             }  
  13.         }  

这样就完成了一个上传显示功能。

这个就是我上传的测试图片。

网友评论

登录后评论
0/500
评论
benjaminwhx
+ 关注