Javascript 在javascript中将图像转换为二进制数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5420384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert an image into binary data in javascript
提问by simplyblue
Possible Duplicates:
Get image data in Javascript?
How to encode image data within an HTML file?
Is there any way to convert an image to binary data in javascript and vice versa.
有没有办法在javascript中将图像转换为二进制数据,反之亦然。
回答by ThiefMaster
I think Get image data in JavaScript?answers your question:
我认为在 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,/, "");
}
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.
将img
标签传递给这个函数。它将以 base64 编码返回图像。不过它会被重新编码。因此您无法访问原始图像数据。