注意:
仅当图像与页面来自同一域或具有
crossOrigin="anonymous"属性并且服务器支持CORS时,此方法才有效。它也不会给您原始文件,而是一个重新编码的版本。如果您需要结果与原始结果相同,请参见Kaiido的答案。
您将需要创建具有正确尺寸的canvas元素,并使用
drawImage函数复制图像数据。然后,您可以使用该
toDataURL函数获取数据:具有以64为基数编码的图像的url。请注意,图像必须已完全加载,否则您将只获得一个空(黑色,透明)图像。
就像这样。我从未编写过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-enpre the image. var dataURL = canvas.toDataURL("image/png"); return dataURL.replace(/^data:image/(png|jpg);base64,/, "");}获取JPEG格式的图像在Firefox的旧版本(大约3.5版)上不起作用,因此,如果要支持该功能,则需要检查兼容性。如果不支持编码,则默认为“ image
/ png”。



