本文实例讲述了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>
<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;
}
}
}
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";
}
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>
.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;
}
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"})
})
@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;
}
}
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程序设计有所帮助。