Note: This only works if the image is from the same domain as the page, or has the crossOrigin="anonymous"
attribute and the server supports CORS.
(注意:仅当图像与页面来自同一域或具有crossOrigin="anonymous"
属性并且服务器支持CORS时,此方法才有效。)
It's also not going to give you the original file, but a re-encoded version.(它也不会给您原始文件,而是一个重新编码的版本。)
If you need the result to be identical to the original, see Kaiido's answer .(如果您需要与原始结果相同的结果,请参见Kaiido的答案 。)
You will need to create a canvas element with the correct dimensions and copy the image data with the drawImage
function.
(您将需要创建具有正确尺寸的canvas元素,并使用drawImage
函数复制图像数据。)
Then you can use the toDataURL
function to get a data: url that has the base-64 encoded image.(然后,您可以使用toDataURL
函数获取数据:具有以64为基数编码的图像的url。)
Note that the image must be fully loaded, or you'll just get back an empty (black, transparent) image.(请注意,图像必须已完全加载,否则您将只获得一个空的(黑色,透明)图像。)
It would be something like this.
(就像这样。)
I've never written a Greasemonkey script, so you might need to adjust the code to run in that environment.(我从未编写过Greasemonkey脚本,因此您可能需要调整代码以在该环境中运行。)
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,/, "");
}
Getting a JPEG-formatted image doesn't work on older versions (around 3.5) of Firefox, so if you want to support that, you'll need to check the compatibility.
(获取JPEG格式的图像在Firefox的较早版本(约3.5版)上不起作用,因此,如果要支持该功能,则需要检查兼容性。)
If the encoding is not supported, it will default to "image/png".(如果不支持编码,则默认为“ image / png”。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…