当前位置: 首页 > 编程笔记 >

java实现上传图片进行切割的方法

扶珂
2023-03-14
本文向大家介绍java实现上传图片进行切割的方法,包括了java实现上传图片进行切割的方法的使用技巧和注意事项,需要的朋友参考一下

本文实例讲述了java实现上传图片进行切割的方法。分享给大家供大家参考。具体分析如下:

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

<form method="post" id="mainForm" action="${ctx }/admin/department!save.action" enctype="multipart/form-data">

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

<tr>  

 <td style="width: 100px;">  

     <strong>上传Logo:</strong>  

     <input type="hidden" name="suffix" id="suffix" value="${depart.departmentLogo.suffix }"/>  

 </td>  

 <td style="width: 225px;">  

     <input type="file" name="logoFile" id="logoFile" onchange="checkFile();"/>  

 </td>  

</tr>  

<tr>  

 <td style="width: 100px;"></td>  

 <td style="width: 225px;">  

     <span class="red">(图片格式:jpg,jpeg,bmp,gif,png;</span><br/>  

     <span class="red">推荐大小:1120×80像素)</span>  

 </td>  

</tr>

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

function checkFile(){  

          

        var value = $("#logoFile").val();  

        if(!value){  

            alert("请选择您要上传的图片!");  

            return false;  

        }else{  

            if(value.lastIndexOf(".jpg") != -1){  

                $("#suffix").val("jpg");  

                return true;  

            }else if(value.lastIndexOf(".jpeg") != -1){  

                $("#suffix").val("jpeg");  

                return true;  

            }else if(value.lastIndexOf(".gif") != -1){  

                $("#suffix").val("gif");  

                return true;  

            }else if(value.lastIndexOf(".bmp") != -1){  

                $("#suffix").val("bmp");  

                return true;  

            }else if(value.lastIndexOf(".png") != -1){  

                $("#suffix").val("png");  

                return true;  

            }else{  

                alert("对不起,您上传文件格式有误,请选择指定格式的图片文件上传");  

                return false;  

            }  

        }  

}

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

public String save() throws Exception {  

        HttpServletRequest request = ServletActionContext.getRequest() ;  

        String departId = request.getParameter("id") ;  

        String departName = request.getParameter("name") ;  

        String companyId = request.getParameter("companyId") ;  

        //图片后缀  

        String suffix = request.getParameter("suffix");  

        List<Menu> listMenu = new ArrayList<Menu>() ;  

        Company company = new Company() ;  

        company.setId(Long.valueOf(companyId)) ;  

        if(this.logoFile != null && departName != null && companyId != null && suffix != null){  

            //获取解析图片的ImageReader  

            Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName(suffix);  

            ImageReader imageReader = imageReaders.next();  

            //把图片以字节流的形式传入  

            InputStream logoStream = new BufferedInputStream(new FileInputStream(this.logoFile));  

            //转为图片输入流  

            ImageInputStream imageInputStream = ImageIO.createImageInputStream(logoStream);  

            imageReader.setInput(imageInputStream, true);  

            int imageWidth = imageReader.getWidth(0);  

            //固定高度80  

            int imageHeight = 80;  

            //设置左中右和剩下的宽度  

            int leftWidth = imageWidth / 2;  

            int middleWidth = (imageWidth - leftWidth) / 3;  

            int rightWidth = 5;  

            int retainWidth = imageWidth - leftWidth -middleWidth - 5;  

              

            ImageReadParam readParam = imageReader.getDefaultReadParam();  

            BufferedImage bImage = null;  

            //裁剪左半部分  

            //根据宽和高获得矩形  

            Rectangle leftImageRectangle = new Rectangle(0, 0, leftWidth, imageHeight);  

            readParam.setSourceRegion(leftImageRectangle);  

            bImage = imageReader.read(0, readParam);   

            //字节数组输出流  

            ByteArrayOutputStream leftByteArrayOutputStream = new ByteArrayOutputStream();  

            ImageIO.write(bImage, suffix, leftByteArrayOutputStream);  

            //获得字节数组  

            byte[] leftImageData = leftByteArrayOutputStream.toByteArray();  

            leftByteArrayOutputStream.close();  

            //Hibernate创建一个blob类型  

            Blob leftBlob = Hibernate.createBlob(leftImageData, this.departmentManager.getSession());  

              

            //裁剪中部部分  

            Rectangle middleImageRectangle = new Rectangle(leftWidth, 0 , middleWidth, imageHeight);  

            readParam.setSourceRegion(middleImageRectangle);  

            bImage = imageReader.read(0, readParam);  

              

            ByteArrayOutputStream middleArrayOutputStream = new ByteArrayOutputStream();  

            ImageIO.write(bImage, suffix, middleArrayOutputStream);  

            byte[] middleImageData = middleArrayOutputStream.toByteArray();  

            middleArrayOutputStream.close();  

            Blob middleBlob = Hibernate.createBlob(middleImageData, this.departmentManager.getSession());  

              

            //裁剪右半部分  

            Rectangle rightImageRectangle = new Rectangle(leftWidth + middleWidth, 0, rightWidth, imageHeight);  

            readParam.setSourceRegion(rightImageRectangle);  

            bImage = imageReader.read(0, readParam);  

              

            ByteArrayOutputStream rightArrayOutputStream = new ByteArrayOutputStream();  

            ImageIO.write(bImage, suffix, rightArrayOutputStream);  

            byte[] rightImageData = rightArrayOutputStream.toByteArray();  

            rightArrayOutputStream.close();  

            Blob rightBlob = Hibernate.createBlob(rightImageData, this.departmentManager.getSession());  

              

            //保留部分  

            Rectangle retainRectangle = new Rectangle(leftWidth + middleWidth + rightWidth, 0, retainWidth, imageHeight);  

            readParam.setSourceRegion(retainRectangle);  

            bImage = imageReader.read(0, readParam);  

              

            ByteArrayOutputStream retainArrayOutputStream = new ByteArrayOutputStream();  

            ImageIO.write(bImage, suffix, retainArrayOutputStream);  

            byte[] retainImageData = retainArrayOutputStream.toByteArray();  

            retainArrayOutputStream.close();  

            Blob retainBlob = Hibernate.createBlob(retainImageData, this.departmentManager.getSession());  

              

            if(!departId.equals("") && departId!=null){  

                Department d = this.departmentManager.findById(Long.valueOf(departId)) ;  

                if(this.checkedAuthIds != null){  

                    for(int i=0;i<checkedAuthIds.size();i++){  

                        Menu menu = new Menu() ;  

                        menu.setId(checkedAuthIds.get(i)) ;  

                        listMenu.add(menu) ;  

                    }  

                    d.setMenus(listMenu) ;  

                }  

                d.getDepartmentLogo().setLeftPartImage(leftBlob);  

                d.getDepartmentLogo().setMiddlePartImage(middleBlob);  

                d.getDepartmentLogo().setRightPartImage(rightBlob);  

                d.getDepartmentLogo().setRetainPartImage(retainBlob);  

                d.getDepartmentLogo().setCreateTime(new Date());  

                d.getDepartmentLogo().setSuffix(suffix);  

                d.setName(departName) ;  

                d.setParentId(0L) ;  

                d.setNodeType(1) ;  

                d.setGrade(1) ;  

                d.setCompany(company) ;  

                this.departmentManager.save(d) ;  

            }else{  

                Integer parentNodeType = 0 ;  

                Department dd = new Department() ;  

                if(this.checkedAuthIds!=null && this.checkedAuthIds.size() != 0){  

                    for(int i=0;i<checkedAuthIds.size();i++){  

                        Menu menu = new Menu() ;  

                        menu.setId(checkedAuthIds.get(i)) ;  

                        listMenu.add(menu) ;  

                    }  

                    dd.setMenus(listMenu) ;  

                }else{  

                    dd.setMenus(null) ;  

                }  

                DepartmentLogo departmentLogo = new DepartmentLogo() ;  

                departmentLogo.setCreateTime(new Date());  

                departmentLogo.setLeftPartImage(leftBlob);  

                departmentLogo.setMiddlePartImage(middleBlob);  

                departmentLogo.setRightPartImage(rightBlob);  

                departmentLogo.setRetainPartImage(retainBlob);  

                departmentLogo.setSuffix(suffix);  

                dd.setDepartmentLogo(departmentLogo);  

                dd.getDepartmentLogo().setDepartment(dd);  

                dd.setId(this.departmentManager.findMaxId()+1) ;  

                dd.setName(departName) ;  

                dd.setParentId(0L) ;  

                dd.setNodeType(1) ;  

                dd.setGrade(1) ;  

                dd.setOrderType(0) ;  

                dd.setCompany(company) ;  

                dd.setFlag(0) ;  

                this.departmentManager.save(dd) ;  

            }  

        }  

        return "reload";  

}

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

<style type="text/css">  

.welcome-hide{width: 210px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;}  

#leftLogo{background: url(${ctx }/admin/department-logo!showLogo.action?position=left) no-repeat;width: ${leftWidth}px;height: 80px;}  

#middleLogo{background: url(${ctx }/admin/department-logo!showLogo.action?position=middle) no-repeat;width: ${middleWidth}px;height: 80px;}  

#rightLogo,#topTableStyle{background: url(${ctx }/admin/department-logo!showLogo.action?position=right) repeat-x;height: 80px;}  

#retainLogo{background: url(${ctx }/admin/department-logo!showLogo.action?position=retain) no-repeat;width: ${retainWidth}px;height: 80px;}  

</style>

department-logo!showLogo.action中的showLogo方法就是加载图片的方法

public String showLogo() {  

          

        HttpServletRequest request = ServletActionContext.getRequest();  

        LoginUser loginUser = (LoginUser)((SecurityContext)request.getSession().  

                getAttribute("SPRING_SECURITY_CONTEXT")).getAuthentication().getPrincipal();  

        List<DepartmentLogo> logos = this.logoManager.findAll();  

        for (DepartmentLogo departmentLogo : logos) {  

            if (loginUser.getUser().getDepartment().getId().equals(departmentLogo.getDepartment().getId())) {  

                String param = request.getParameter("position");  

                Blob blob = null;  

                if (param != null) {  

                    try {  

                        if (param.equals("left")) {  

                            blob = departmentLogo.getLeftPartImage();  

                            imageLogo = blob.getBinaryStream();  

                            return "showLogo";  

                        }else if (param.equals("middle")) {  

                            blob = departmentLogo.getMiddlePartImage();  

                            imageLogo = blob.getBinaryStream();  

                            return "showLogo";  

                        }else if (param.equals("right")) {  

                            blob = departmentLogo.getRightPartImage();  

                            imageLogo = blob.getBinaryStream();  

                            return "showLogo";  

                        }else if (param.equals("retain")) {  

                            blob = departmentLogo.getRetainPartImage();  

                            imageLogo = blob.getBinaryStream();  

                            return "showLogo";  

                        }  

                    } catch (Exception e) {  

                        e.printStackTrace();  

                    }  

                }  

            }  

        }  

        return null;  

}

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

@Results({  

    @Result(name = "showLogo", type = "stream", params = {"contentType", "image/jpeg,"  

            + "image/bmp,image/png,image/gif,image/jpeg",   

            "inputName", "imageLogo", "bufferSize", "4096"})  

})

那么top.jsp中的width是怎么得到的呢?
实在加载菜单的时候得到的,下面是menu中的方法

HttpServletRequest request = ServletActionContext.getRequest();  

List<DepartmentLogo> logos = this.logoManager.findAll();  

for (DepartmentLogo departmentLogo : logos) {  

    if (user.getDepartment().getId().equals(departmentLogo.getDepartment().getId())) {  

 request.setAttribute("leftWidth", ImageIO.read(departmentLogo.  

  getLeftPartImage().getBinaryStream()).getWidth());  

 request.setAttribute("middleWidth", ImageIO.read(departmentLogo.  

  getMiddlePartImage().getBinaryStream()).getWidth());  

 request.setAttribute("retainWidth", ImageIO.read(departmentLogo.  

  getRetainPartImage().getBinaryStream()).getWidth());  

 break;  

    }  

}

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

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

希望本文所述对大家的Java程序设计有所帮助。

 类似资料:
  • 本文向大家介绍C#实现图片上传与浏览切换的方法,包括了C#实现图片上传与浏览切换的方法的使用技巧和注意事项,需要的朋友参考一下 本文以一个完整实例讲述了C#实现图片上传与浏览切换的方法,对于进行C#程序设计来说具有一定的借鉴价值。分享给大家供大家参考。 具体实现代码如下: 希望本文实例对大家的C#程序设计有所帮助。

  • 本文向大家介绍php实现图片上传、剪切功能,包括了php实现图片上传、剪切功能的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家详细介绍了php实现图片上传、剪切功能的具体代码,供大家参考,具体内容如下 以上就是本文的全部内容,希望对大家学习php程序设计有所帮助。

  • 本文向大家介绍Yii+upload实现AJAX上传图片的方法,包括了Yii+upload实现AJAX上传图片的方法的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了Yii+upload实现AJAX上传图片的方法。分享给大家供大家参考,具体如下: 控制器代码: VIEW代码: 更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《sm

  • 本文向大家介绍java实现多图片上传功能,包括了java实现多图片上传功能的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了java实现多图片上传功能的具体代码,供大家参考,具体内容如下 开发环境:jdk1.7,MyEclipse10 框架用的是spring。用到了maven工具(maven的包百度下就可以)。 四步完成,全部复制改参数就可以 第一步:先在Spring中对图片进行限制

  • 本文向大家介绍Java微信小程序oss图片上传的实现方法,包括了Java微信小程序oss图片上传的实现方法的使用技巧和注意事项,需要的朋友参考一下 先将图片上传到服务器,再将服务器上的图片传入oss中 小程序js Java后台 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持呐喊教程。

  • 本文向大家介绍c#图片上传和显示的实现方法,包括了c#图片上传和显示的实现方法的使用技巧和注意事项,需要的朋友参考一下 由于需要图片上传的功能,所以花了一些时间网上找相关资料终于搞定,效果图如下: 下面的是解决方案截图和上传的图片截图: 具体实现代码如下: 1.界面代码 2.后台代码UploadPic.aspx.cs 3.最后防止上传大文件图片时报错,配置文件添加配置Web.config 以上就是