This article describes the method of uploading images for cutting by Java. Share it for your reference. The specific analysis is as follows:
Why do I want to cut the uploaded pictures? The pictures in my project are department logos. Each department can choose a different logo, but to deal with browser compatibility and stretching, I chose to cut an image into The left, middle, right and the rest of the parts, because the left and middle changes may have patterns or characters, so they cannot be stretched. The stretched only the right part, and the remaining part can be adapted. So I used the ImageReader of javax to operate. Finally, save the database as blob type.
First, write enctype="multipart/form-data" in the form form
Copy the code code as follows:<form method="post" id="mainForm" action="${ctx }/admin/department!save.action" enctype="multipart/form-data">
The following is the following code for uploading component copying code in the form: <tr>
<td>
<strong>Upload Logo:</strong>
<input type="hidden" name="suffix" id="suffix" value="${depart.departmentLogo.suffix }"/>
</td>
<td>
<input type="file" name="logoFile" id="logoFile" onchange="checkFile();"/>
</td>
</tr>
<tr>
<td></td>
<td>
<span>(Image format: jpg,jpeg,bmp,gif,png;</span><br/>
<span>Recommended size: 1120×80 pixels)</span>
</td>
</tr>
The checkFile() method of image checking is used to check whether the image ends in a specified format and whether there is no copy code code selected as follows: 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, the file format you uploaded is incorrect, please select the image file in the specified format to upload");
return false;
}
}
}
The following is the background save operation.
Copy the code as follows: 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 the ImageReader for parsing the image
Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName(suffix);
ImageReader imageReader = imageReaders.next();
//Pass the image in the form of a 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 80
int imageHeight = 80;
//Set left, center, right and remaining width
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;
//Crop the left half
//Get rectangle based on width and height
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 creates 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 the 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());
//Reserve 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));
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";
}
The following is shown. I use qui, so the copy code is dynamically displayed in the css above top.jsp as follows: <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 to load the picture and copy the code code as follows: 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 be selected as type="stream" in struts2
Copy the code as follows: @Results({
@Result(name = "showLogo", type = "stream", params = {"contentType", "image/jpeg,"
+ "image/bmp,image/png,image/gif,image/jpeg",
"inputName", "imageLogo", "bufferSize", "4096"})
})
So how do you get the width in top.jsp?
I got it when loading the menu. The following is the method in the menu copy the code code as follows: 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 image I uploaded.
I hope this article will be helpful to everyone's Java programming.