Java implementation to upload images for cutting

Source: Internet
Author: User

Why do I have to upload the image to cut it, my picture of this project is the department logo, each department can choose a different logo, but to deal with the browser compatibility and stretching, I chose to cut a picture into left, middle, right and the rest of the section, Because the left and the middle change may have the pattern or the word so can not stretch, the stretching is just the right part, the rest of the part adaptive on it. So I used the javax ImageReader to operate. Finally, the database is saved as a BLOB type.

First, write the enctype= "Multipart/form-data" in the form form.

<form method= "POST" id= "MainForm" action= "${ctx}/admin/department!save.action" enctype= "Multipart/form-data" >

Write the upload component in the form below

<TR><TD style= "width:100px;" ><strong> upload 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" > (image format: Jpg,jpeg,bmp,gif,png;</span><br/><span class= "Red" > Recommended size: 1120 x80 pixels) </span></td></tr>

The Checkfile () method of the picture check is used to check whether the picture ends in a specified format and is not selected

function Checkfile () {var value = $ ("#logoFile"). Val (); if (!value) {alert ("Please select the picture you want to upload!") "); 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 ("Sorry, you uploaded file format is wrong, please select the format of the image file upload"); return false;}}

Here is the save operation in the background.

Public String Save () throws Exception {HttpServletRequest request = Servletactioncontext.getrequest (); String Departid = request.getparameter ("id"); String departname = request.getparameter ("name"); String companyid = Request.getparameter ("CompanyID");//Picture suffix 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) {//Get parse picture imagereaderiterator<imagereader> imagereaders = imageio.getimagereadersbyformatname (suffix); ImageReader imagereader = Imagereaders.next ();// Pass the picture in the form of byte stream inputstream Logostream = new Bufferedinputstream (new FileInputStream (This.logofile));// Convert to picture input stream Imageinputstream Imageinputstream = Imageio.createimageinputstream (Logostream); Imagereader.setinput ( Imageinputstream, true); int imagewidth = imagereader.getwidth (0);//fixed height 80int imageheight = 80;//set left middle right and remaining width int leftwidth = Imagewidth/2;int Middlewidth = (imagewidth-leftwidth)/3;int rightwidth = 5;int retain Width = Imagewidth-leftwidth-middlewidth-5;imagereadparam Readparam = Imagereader.getdefaultreadparam (); BufferedImage bimage = null;//clipping left half//based on width and height get rectangle Rectangle leftimagerectangle = new Rectangle (0, 0, Leftwidth, imageheight ); Readparam.setsourceregion (leftimagerectangle); bimage = Imagereader.read (0, Readparam); byte array output stream Bytearrayoutputstream Leftbytearrayoutputstream = new Bytearrayoutputstream (); Imageio.write (bImage, suffix , leftbytearrayoutputstream);//Get byte array byte[] Leftimagedata = Leftbytearrayoutputstream.tobytearray (); Leftbytearrayoutputstream.close ();//hibernate Create a blob type blob Leftblob = Hibernate.createblob (Leftimagedata, This.departmentManager.getSession ());//Crop the middle part 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 ());//crop right half 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 ());//Reserved Part 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)); 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;D epartment dd = new Department (); if (This.checkedauthids!=null && this.checkedau Thids.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 ();d epartmentlogo.setcreatetime (New Date ()); Departmentlogo.setleftpartimage (Leftblob);d epartmentlogo.setmiddlepartimage (MIDDLEBLOB); Departmentlogo.setrightpartimage (Rightblob);d epartmentlogo.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";}

Here is the display, I am using the qui, so in the top.jsp above the CSS for dynamic display

<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>
The Showlogo method in Department-logo!showlogo.action is the way to load pictures

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;}

Of course, the returned address should choose the type= "stream" in Struts2

@Results ({@Result (name = "Showlogo", type = "Stream", params = {"ContentType", "image/jpeg," + "image/bmp,image/png,image /gif,image/jpeg "," InputName "," Imagelogo "," buffersize "," 4096 "})})

So how does the width of the top.jsp get?

When the menu is loaded, the following methods are available

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;}}

This completes an upload display function.

This is the test picture I uploaded.

Java implementation to upload images for cutting

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.