0

有人知道吗,是否可以从远程 URL 将图像读取为二进制文件。我知道 File API 让我们有可能从本地系统读取二进制文件。但我找不到有关从远程 URL 读取的信息。也许我什至可以从浏览器缓存中读取这些信息,在我加载这个信息之后,或者其他?

4

1 回答 1

1

我认为这将解决您的问题,使用您的网址作为 SRC 制作一个 img 标签。

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,/, "");
}

这个函数是在Get image data in JavaScript? 上找到的?

像这样使用它

var img = new Image();
img.load = function(){
    var data = getBase64Image(this);
};
img.src= "my IMAGE URL";

或者使用您自己的 HTML 中的 img 标签

于 2011-11-16T15:53:44.663 回答