欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-31 16:35:46
本文实例讲述了java实现上传图片进行切割的方法。分享给大家供大家参考。具体分析如下: 为什么我要进行上传的图片进行切割呢,我这个项目的图片是部门logo,每个部门都可以...

本文实例讲述了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实现上传图片进行切割的方法

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

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