如何将Canvas图像转换为缓冲图像以进行Servlet处理?

时间:2018-08-06 22:47:10

标签: javascript ajax servlets html5-canvas

我需要将HTML-Canvas图像从网页发送到Servlet进行图像处理。在我的网页上,这是通过上传jpg或png图像,然后单击处理按钮来完成的。

我的前端正在工作(我可以上传和显示图像),但是我不知道如何将图像从网页发送到服务器,反之亦然。

你能帮我吗?

HTML:(img存储在画布中)

 <canvas id="canvas"></canvas>

JavaScript:

var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {

        // Ajax Code here???

    }
  };
  xhttp.open("GET", ?, true);
  xhttp.send();

enter image description here

2 个答案:

答案 0 :(得分:2)

不幸的是,并非所有浏览器都支持Canvas.toBlob()功能。例如,MS Edge和其他浏览器不支持它(请参阅browser compatibility)。因此,我们必须使用Canvas.toDataURL()函数。

我为您编写了解决方案,其功能与从HTML发送表单一样:

var canvas = document.getElementById('canvas'),
    dataURL = canvas.toDataURL('image/jpeg', 0.7), //or canvas.toDataURL('image/png');
    blob = dataURItoBlob(dataURL),
    formData = new FormData(),
    xhr = new XMLHttpRequest();

//We append the data to a form such that it will be uploaded as a file:
formData.append('canvasImage', blob);
//'canvasImage' is a form field name like in (see comment below).
xhr.open('POST', 'jsp-file-on-your-server.jsp');
xhr.send(formData);
//This is the same like sending with normal form:
//<form method="post" action="jsp-file-on-your-server.jsp" enctype="multipart/form-data">
//    <input type="file" name="canvasImage"/>
//</form>

function dataURItoBlob(dataURI)
{
    var aDataURIparts = dataURI.split(','),
        binary = atob(aDataURIparts[1]),
        mime = aDataURIparts[0].match(/:(.*?);/)[1],
        array = [],
        n = binary.length,
        u8arr = new Uint8Array(n);

    while(n--)
        u8arr[n] = binary.charCodeAt(n);

    return new Blob([u8arr], {type: mime})
}

如果您不知道如何使用JSP在服务器端保存文件,请阅读:

答案 1 :(得分:0)

var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var canvas = document.getElementById('canvas');
        canvas.toBlob(function(blob) { 
            var oReq = new XMLHttpRequest();
            oReq.open("POST", /*URL*/, true);
            oReq.onload = function (oEvent) {
              // Uploaded.
            };
            oReq.send(blob);
        },'image/jpeg', 0.95);

    }
  };
  xhttp.open("GET", ?, true);
  xhttp.send();

更多信息:CanvasElement toBlobSending Blob