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

Javascript / jQuery - How to convert Media and Image data into binary text format

本文关键字:转换 数据 二进制 格式 文本 图像 jQuery- 媒体 Javascript      更新时间:2023-09-26

我需要通过json发送图像/媒体,因为需要将其转换为文本格式。如何通过jQuery/Javascript实现这一点?

您可以在这篇文章中找到答案,在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,/, "");
}

您需要将img标记传递给此函数。有关更多详细信息,请参阅在javascript 中将图像转换为二进制数据

我已经读过几次jQuery不提供下载二进制数据并将其作为字符串传递给JavaScript的功能。然后我遇到了这个问题。这让我思考了一下,我在$.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);

换句话说,如果您通读$.ajax()的文档,您只需添加一个dataType"二进制"。

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