解码图像Base64字符串无法正常工作

时间:2015-11-12 23:07:05

标签: javascript java image base64 byte

我需要一种方法从客户端压缩选定的图像然后将其发送到服务器,我在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:无效的JPEG文件结构:两个SOF标记或两个soi等 它几次没有写入字节但是图像每次都被破坏了,它显示的是灰色图像而不是原始图像。

1 个答案:

答案 0 :(得分:0)

我解决了。我需要做的是使用javascript方法encodeURIComponent()为basel编码base64。所以发送base64字符串的代码如下所示:

function  sendImage(base64){
    var query = "number=0&id=012&base64="+encodeURIComponent(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);
}