【发布时间】:2015-11-12 23:07:04
【问题描述】:
我需要一种方法来从客户端压缩选定的图像,然后将其发送到服务器,我在 img.onload 中提出了以下代码:
var canvas = document.createElement('canvas');
var img = document.createElement("img");
img.src = url;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > max_width) {
//height *= max_width / width;
height = Math.round(height *= max_width / width);
width = max_width;
}
} else {
if (height > max_height) {
width = Math.round(width *= max_height / height);
height = max_height;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var base64 = canvas.toDataURL("image/jpeg");
然后我使用ajax发送base64如下:
function sendImage(base64){
var query = "number=0&id=012&base64="+base64;
var url = "myImage.jsp";
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = postImgAjax;
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", query.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(query);
}
在 myImage.jsp 中,我使用以下内容来解码 Base64 字符串:
String imgBase64 = request.getParameter("base64");
//BASE64Decoder d = new BASE64Decoder();
String str = (imgBase64.split(",")[1]);
//str = str.replaceAll(" ", "");
//System.out.println("\n "+str.replaceAll("\n", ""));
byte[] imgBytes = Base64.decodeBase64(str.getBytes());
//d.decodeBuffer(str.replaceAll("\\s", ""));
//DatatypeConverter.parseBase64Binary(str.replaceAll("\\s", ""));
Utils.save(imgBytes);
我花了几个小时试图完成这项工作,我尝试了很多可能性(比如使用不同的解码器包,删除空格等)它不断抛出 javax.imageio.IIOException: Invalid JPEG file structure: two SOF marker or两个soi等。 它几次写入字节,但图像每次都损坏,它显示的是灰色图像而不是原始图像。
【问题讨论】:
-
如果正确的数据从网页发送并在服务器上接收,您是否检查过调试器?
-
同意,首先要检查的是发送端和接收端的base64数据,然后就可以定位问题了。您应该能够首先编码一个较小的 jpeg 以便更容易调查 - 使用已知的 base64 等效
-
为什么要拆分base64参数?您确定在 str.getBytes() 中使用的基本字符集与发送的相同。尝试使用 javascript 的 btoa 方法,看看是否更好。
-
您好,感谢您的回复。是的,在服务器中接收到的base64的相同内容。实际上,我使用 str.getBytes() 是因为 apache common 包中的解码器不直接获取字符串
-
我是 javascript 新手,不知道如何在 canvas 中使用 btoa 方法。
标签: javascript java image base64 byte