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

网友投稿 237 2023-08-04


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

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

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

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

复制代码 代码如下:

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

复制代码 代码如下:

 

     上传Logo: 

      

 

 

      

 

 

 

     (图片格式:jpg,jpeg,bmp,gif,png;
 

     推荐大小:112080像素) 

 

图片检查的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

        Company company = new Company() ; 

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

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

            //获取解析图片的ImageReader 

            Iterator 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

                        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

                        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中进行动态显示

复制代码 代码如下:

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 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")) { 

           http://                 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(); 

          &http://nbsp;                 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 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程序设计有所帮助。

                        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

                        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中进行动态显示

复制代码 代码如下:

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 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")) { 

           http://                 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(); 

          &http://nbsp;                 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 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程序设计有所帮助。

                        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中进行动态显示

复制代码 代码如下:

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 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")) { 

           http://                 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(); 

          &http://nbsp;                 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 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程序设计有所帮助。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java从数据库中读取Blob对象图片并显示的方法
下一篇:Java操作Mysql的方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~