需求:想在用户上传大图片之前压缩,否则上传图片太大,影响等待时间。
感谢这篇博客。
http://blog.youkuaiyun.com/renfufei/article/details/9836317
并且在stackoverflow上找到这篇文章
http://stackoverflow.com/questions/2303690/resizing-an-image-in-an-html5-canvas
两篇文档结合一下出了如下的Demo:
前端页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
// returns a function that calculates lanczos weight
function lanczosCreate(lobes) {
return function(x) {
if (x > lobes)
return 0;
x *= Math.PI;
if (Math.abs(x) < 1e-16)
return 1;
var xx = x / lobes;
return Math.sin(x) * Math.sin(xx) / x / xx;
};
}
// elem: canvas element, img: image element, sx: scaled width, lobes: kernel radius
function thumbnailer(elem, img, sx, lobes) {
this.canvas = elem;
elem.width = img.width;
elem.height = img.height;
elem.style.display = "none";
this.ctx = elem.getContext("2d");
this.ctx.drawImage(img, 0, 0);
this.img = img;
this.src = this.ctx.getImageData(0, 0, img.width, img.height);
this.dest = {
width : sx,
height : Math.round(img.height * sx / img.width),
};
this.dest.data = new Array(this.dest.width * this.dest.height * 3);
this.lanczos = lanczosCreate(lobes);
this.ratio = img.width / sx;
this.rcp_ratio = 2 / this.ratio;
this.range2 = Math.ceil(this.ratio * lobes / 2);
this.cacheLanc = {};
this.center = {};
this.icenter = {};
setTimeout(this.process1, 0, this, 0);
}
thumbnailer.prototype.process1 = function(self, u) {
self.center.x = (u + 0.5) * self.ratio;
self.icenter.x = Math.floor(self.center.x);
for (var v = 0; v < self.dest.height; v++) {
self.center.y = (v + 0.5) * self.ratio;
self.icenter.y = Math.floor(self.center.y);
var a, r, g, b;
a = r = g = b = 0;
for (var i = self.icenter.x - self.range2; i <= self.icenter.x + self.range2; i++) {
if (i < 0 || i >= self.src.width)
continue;
var f_x = Math.floor(1000 * Math.abs(i - self.center.x));
if (!self.cacheLanc[f_x])
self.cacheLanc[f_x] = {};
for (var j = self.icenter.y - self.range2; j <= self.icenter.y + self.range2; j++) {
if (j < 0 || j >= self.src.height)
continue;
var f_y = Math.floor(1000 * Math.abs(j - self.center.y));
if (self.cacheLanc[f_x][f_y] == undefined)
self.cacheLanc[f_x][f_y] = self.lanczos(Math.sqrt(Math.pow(f_x * self.rcp_ratio, 2)
+ Math.pow(f_y * self.rcp_ratio, 2)) / 1000);
weight = self.cacheLanc[f_x][f_y];
if (weight > 0) {
var idx = (j * self.src.width + i) * 4;
a += weight;
r += weight * self.src.data[idx];
g += weight * self.src.data[idx + 1];
b += weight * self.src.data[idx + 2];
}
}
}
var idx = (v * self.dest.width + u) * 3;
self.dest.data[idx] = r / a;
self.dest.data[idx + 1] = g / a;
self.dest.data[idx + 2] = b / a;
}
if (++u < self.dest.width)
setTimeout(self.process1, 0, self, u);
else
setTimeout(self.process2, 0, self);
};
thumbnailer.prototype.process2 = function(self) {
self.canvas.width = self.dest.width;
self.canvas.height = self.dest.height;
self.ctx.drawImage(self.img, 0, 0, self.dest.width, self.dest.height);
self.src = self.ctx.getImageData(0, 0, self.dest.width, self.dest.height);
var idx, idx2;
for (var i = 0; i < self.dest.width; i++) {
for (var j = 0; j < self.dest.height; j++) {
idx = (j * self.dest.width + i) * 3;
idx2 = (j * self.dest.width + i) * 4;
self.src.data[idx2] = self.dest.data[idx];
self.src.data[idx2 + 1] = self.dest.data[idx + 1];
self.src.data[idx2 + 2] = self.dest.data[idx + 2];
}
}
self.ctx.putImageData(self.src, 0, 0);
self.canvas.style.display = "block";
sendImage(self.canvas);
};
function upload(){
var docObj = document.getElementById("upfile");
var imgObjPreview = new Image();
if (docObj.files && docObj.files[0]) {
imgObjPreview.onload = function() {
var canvas = document.createElement("canvas");
new thumbnailer(canvas, imgObjPreview, 10, 3); //this produces lanczos3
}
imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
}
}
window.onload = function(){
//var img = document.getElementById("myimg");
//var src = img.getAttribute('src');
//img.setAttribute('src','');
//img.onload = function(){
// but feel free to raise it up to 8. Your client will appreciate
// that the program makes full use of his machine.
//document.body.appendChild(canvas);
//sendImage(canvas);
//};
//img.setAttribute('src',src);
}
// 上传图片,jQuery版
function sendImage(canvas){
console.log(canvas);
// 获取Base64编码后的图像数据,格式是字符串
// "data:image/png;base64,"开头,需要在客户端或者服务器端将其去掉,后面的部分可以直接写入文件。
var dataurl = canvas.toDataURL("image/png");
// 为安全 对URI进行编码
// data%3Aimage%2Fpng%3Bbase64%2C 开头
var imagedata = encodeURIComponent(dataurl);
// 因为是string,所以服务器需要对数据进行转码,写文件操作等。
// 个人约定,所有http参数名字全部小写
console.log(dataurl);
//console.log(imagedata);
var data = {
imagename: "myImage.png",
imagedata: imagedata
};
jQuery.ajax( {
url : "receive.jsp",
data : data,
type : "POST",
// 期待的返回值类型
dataType: "json",
complete : function(xhr,result) {
//console.log(xhr.responseText);
if(!xhr){
alert('网络连接失败!');
return false;
}
var text = xhr.responseText;
if(!text){
alert('网络错误!');
return false;
}
var json = eval("("+text+")");
if(!json){
alert('解析错误!');
return false;
} else {
alert(json.message);
}
//console.dir(json);
//console.log(xhr.responseText);
}
});
};
</script>
</head>
<body>
<input type="file" οnchange="upload()" id="upfile" />
</body>
</html>
JSP服务端页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="sun.misc.BASE64Decoder"%>
<%@page import="java.io.*"%>
<%@page import="java.net.URLDecoder"%>
<%!
// 本文件:/receive.jsp
// 图片存放路径
String photoPath = "D:/photo/";
File photoPathFile = new File(photoPath);
// references: http://blog.youkuaiyun.com/remote_roamer/article/details/2979822
private boolean saveImageToDisk(byte[] data,String imageName) throws IOException{
int len = data.length;
//
// 写入到文件
FileOutputStream outputStream = new FileOutputStream(new File(photoPathFile,imageName));
outputStream.write(data);
outputStream.flush();
outputStream.close();
//
return true;
}
private byte[] decode(String imageData) throws IOException{
BASE64Decoder decoder = new BASE64Decoder();
byte[] data = decoder.decodeBuffer(imageData);
for(int i=0;i<data.length;++i)
{
if(data[i]<0)
{
//调整异常数据
data[i]+=256;
}
}
//
return data;
}
%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
//如果是IE,那么需要设置为text/html,否则会弹框下载
//response.setContentType("text/html;charset=UTF-8");
response.setContentType("application/json;charset=UTF-8");
//
String imageName = request.getParameter("imagename");
String imageData = request.getParameter("imagedata");
int success = 0;
String message = "";
if(null == imageData || imageData.length() < 100){
// 数据太短,明显不合理
message = "fail,data didnt exits";
} else {
// 去除开头不合理的数据
imageData = imageData.substring(30);
imageData = URLDecoder.decode(imageData,"UTF-8");
//System.out.println(imageData);
byte[] data = decode(imageData);
int len = data.length;
int len2 = imageData.length();
if(null == imageName || imageName.length() < 1){
imageName = System.currentTimeMillis()+".png";
}
saveImageToDisk(data,imageName);
//
success = 1;
message = "success,paramslength:"+len2+"char,decodesize:"+len+"byte";
}
// 后台打印
System.out.println("message="+message);
%>
{
"message": "<%=message %>",
"success": <%=success %>
}