Javascript / jQuery - 如何将媒体和图像数据转换为二进制文本格式

时间:2013-02-06 10:27:41

标签: javascript jquery

我需要通过json发送图像/媒体,因为转换需要以文本格式进行。我怎样才能通过jQuery / Javascript实现这一目标?

2 个答案:

答案 0 :(得分:1)

你可以在这篇文章中找到答案get image data in javascript

function getBase64Image(img) { // Create an empty canvas element var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height;

// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);

// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to guess the
// original format, but be aware the using "image/jpg" will re-encode the image.
var dataURL = canvas.toDataURL("image/png");

return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");

// Copy the image contents to the canvas var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); // Get the data-URL formatted image // Firefox supports PNG and JPEG. You could check img.src to guess the // original format, but be aware the using "image/jpg" will re-encode the image. var dataURL = canvas.toDataURL("image/png"); return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
你需要将img标签传递给这个函数。 有关详细信息,请参阅Convert an image into binary data in javascript

答案 1 :(得分:0)

我已经读过几次jQuery不提供下载二进制数据的功能,并将其作为字符串传递给JavaScript。然后我遇到了this question。这让我思考,我写了一个围绕$.ajax()的包装器看起来像这样(是的,它被简化为显示主要位):

ajaxWrapper = function(url, dataType, callback, headers) {
    return $.ajax({
        url: url,
        dataType: dataType == "binary" ? "text" : dataType,
        mimeType: dataType == "binary" ? "text/plain; charset=x-user-defined" : undefined,
        headers: headers || {}
    }).done(function(data, status, jqXHR) {
        callback(data, status, jqXHR);
    });
}

然后,如果您正在处理Unicode,则回调包含以下行:

data = btoa(unescape(encodeURIComponent(data)));

或其他简单

data = btoa(data);

换句话说,如果您通读documentation of $.ajax(),则只需添加dataType“二进制”。

请注意,我使用的是jQuery 1.7.1,但我不明白为什么它在以后的版本中也不适用。