【问题标题】:Convert an image into binary data in javascript [duplicate]在javascript中将图像转换为二进制数据[重复]
【发布时间】:2011-07-22 04:19:26
【问题描述】:

可能的重复:
Get image data in Javascript?
How to encode image data within an HTML file?

有没有什么方法可以在javascript中将图像转换为二进制数据,反之亦然。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    我认为Get image data in JavaScript? 回答了你的问题:

    // Code taken from MatthewCrumley (https://stackoverflow.com/a/934925/298479)
    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 标签传递给这个函数。它将以 base64 编码返回图像。它将被重新编码。所以你无法访问原始图像数据。

    【讨论】:

    • 击败我,但我也是这样做的。 +1
    • 我在这里把它变成了一个书签:jsfiddle.net/bgmort/m26yr 你在它自己的标签中打开你想要的图像,然后运行它,它会在屏幕上插入一个带有数据 url 的文本区域。
    • 您可以使用“dataURL.split(',')[1]”代替“dataURL.replace”,这也适用于“png”或“jpg”以外的其他格式。 :)
    • 这是一个 base64 编码,而不是文件所需的直接二进制
    • 嗯.. 不使用画布来获取 base64 图像数据的方法怎么样?可能吗?
    猜你喜欢
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多