在javascript中将图像转换为二进制数据 [英] Convert an image into binary data in javascript

查看:1483
本文介绍了在javascript中将图像转换为二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

使用Javascript获取图像数据?

如何在HTML文件中编码图像数据?

有没有办法在javascript中将图像转换为二进制数据,反之亦然。

Is there any way to convert an image to binary data in javascript and vice versa.

推荐答案

我认为用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编码返回图像。它将被重新编码。因此您无法访问原始图像数据。

Pass the img tag to this function. It will return the image in base64 encoding. It will be re-encoded though. So you cannot access the original image data.

这篇关于在javascript中将图像转换为二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆