页面压缩图片
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%><%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.10.2.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/lrz.mobile.min.js"></script>
<script type="text/javascript">
function compress(_this){
lrz(_this.files[0],{width:153,quality:0.9},function(rst){
var show_img = new Image();
show_img.src = rst.base64;
$("#img_show").html("<div id='upimg'></div>");
$("#upimg").html(show_img);
$("#src").val(show_img.src);
_this.src = show_img.src;
});
}
</script>
<title>Insert title here</title>
</head>
<body>
<h1>上传页面</h1>
<s:actionerror/>
<s:fielderror />
<form method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath }/upload.action">
上传文件 <!-- <input type="file" name="upload" /> -->
<input type="submit" value="上传" />
<br/>
<input type="file" name="upload" οnchange="compress(this)">
<input id="src" name="src" >
<div id="img_show"></div>
</form>
</body>
</html>
图片以流的方式传到后台,再将流保存成图片,完成
package cn.itcast.struts2.demo1;
import java.io.FileOutputStream;
import java.io.OutputStream;
import sun.misc.BASE64Decoder;
import com.opensymphony.xwork2.ActionSupport;
/**
* 完成文件上传 (不是解析上传内容,因为上传内容 由fileUpload拦截器负责解析)
*
* @author seawind
*
*/
public class UploadAction extends ActionSupport {
private String src;//图片流
static BASE64Decoder decoder = new sun.misc.BASE64Decoder();
@Override
public String execute() throws Exception {
System.out.println(src.substring(23));
GenerateImage(src.substring(23));
return NONE;
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
//base64字符串转化成图片
public static boolean GenerateImage(String imgStr)
{ //对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) //图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try
{
//Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{//调整异常数据
b[i]+=256;
}
}
//生成jpeg图片
String imgFilePath = "d://222.jpg";//新生成的图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
}
catch (Exception e)
{
return false;
}
}
}
代码案例:http://download.csdn.net/detail/lingxun123456/9650166