使用javascript将图像dataUrl转换为用于AJAX POST的Blob图像

时间:2015-04-07 20:10:07

标签: javascript jquery base64 binary-image

我有以下代码,它将拍摄图像,允许用户裁剪(使用其他代码未显示或此问题所需),然后从画布渲染base64中的图像。

我需要能够将图像转换为二进制文件,因为提交给它的API端点不能使用base64。我有转换为Blob的功能,但我不确定如何正确实现它:

$(function () {
var fileInput = document.getElementById("file"),
    renderButton = $("#renderButton"),
    submit = $(".submit"),
    imgly = new ImglyKit({
        container: "#container",
        ratio: 1 / 1
    });

// As soon as the user selects a file...
fileInput.addEventListener("change", function (event) {
    var file;

    var fileToBlob = event.target.files[0];
    var blob = new Blob([fileToBlob], {
        "type": fileToBlob.type
    });

    // do stuff with blob
    console.log(blob);

    // Find the selected file
    if (event.target.files) {
        file = event.target.files[0];
    } else {
        file = event.target.value;
    }

    // Use FileReader to turn the selected
    // file into a data url. ImglyKit needs
    // a data url or an image

    var reader = new FileReader();
    reader.onload = (function (file) {
        return function (e) {
            data = e.target.result;

            // Run ImglyKit with the selected file
            try {
                imgly.run(data);
            } catch (e) {
                if (e.name == "NoSupportError") {
                    alert("Your browser does not support canvas.");
                } else if (e.name == "InvalidError") {
                    alert("The given file is not an image");
                }
            }
        };
    })(file);

    reader.readAsDataURL(file);
});

// As soon as the user clicks the render button...
// Listen for "Render final image" click
renderButton.click(function (event) {
    var dataUrl;


    imgly.renderToDataURL("image/jpeg", {
        size: "1200"
    }, function (err, dataUrl) {
        // `dataUrl` now contains a resized rendered image

        //Convert DataURL to Blob to send over Ajax
        function dataURItoBlob(dataUrl) {
            // convert base64 to raw binary data held in a string
            var byteString = atob(dataUrl.split(',')[1]);

            // separate out the mime component
            var mimeString = dataUrl.split(',')[0].split(':')[1].split(';')[0];

            // write the bytes of the string to an ArrayBuffer
            var ab = new ArrayBuffer(byteString.length);
            var ia = new Uint8Array(ab);
            for (var i = 0; i < byteString.length; i++) {
                ia[i] = byteString.charCodeAt(i);
            }

            // write the ArrayBuffer to a blob, and you're done
            //var bb = new BlobBuilder();
            //bb.append(ab);
            //return bb.getBlob(mimeString);
            return new Blob([ab], {
                type: 'image/jpeg'
            });
        }


        var blob = dataURItoBlob(dataUrl);
        //console.log("var blob: " + blob);
        //var fd = new FormData(document.forms[0]);

        var image = $("<img><br>").attr({
            src: dataUrl
        });

        image.appendTo($(".result"))
        $removeButton = $('<button class="btn btn-default remove">')
            .text('Remove ' + imageid.value).appendTo($(".result"))
            .on('click', function () {
              panel.remove();
              $(this).remove();
              return false;
            });


        $submitButton = $('<div class="btn btn-default submit"></div>')
            .text('Submit ' + imageid.value).appendTo($(".result"))
            .on('click', function () {
              var fd = new FormData;
              fd.append('file', blob, 'image.png');
              //console.log("var fd: " + fd);
              var xhr = new XMLHttpRequest();
              var saveImage = encodeURIComponent(dataUrl);
              //console.log("SAVE IMAGE: " + saveImage);
              //console.log(saveImage);
              fd.append("myFile", blob);
              xhr.open('POST', 'http://url.com/rest/v1/utils/guid/encode?' + saveImage + '&imageid=' + imageid.value, true);
              xhr.send(fd);
            });
    });
});
});

在提交时,我在控制台中收到以下内容:

  

http://url.com/rest/v1/utils/guid/encode?data%3Aimage%2Fjpeg%3Bbase64%2C%2F ... CiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP%2FZ

jsFiddle 中的当前版本:LINK

0 个答案:

没有答案