简体   繁体   English

Javascript-可以对远程映像进行base64吗?

[英]Javascript - Is it possible to base64 a remote image?

I have the following 我有以下

HTML 的HTML

<img id="preview1" crossorigin="anonymous" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">

JS JS

var img = document.getElementById("preview1");
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.width;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
var result = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
console.log(result)

For some reason, when I paste the result (base64) in an img src it shows nothing. 由于某种原因,当我将result (base64)粘贴到img src它什么也没有显示。 Also when I paste the result (base64) as a url, it shows nothing. 另外,当我将result (base64)粘贴为url时,它什么也没有显示。

When I use use input="file" and use FileReader() to get the file. 当我使用input="file"并使用FileReader()获取文件时。 it works fine. 它工作正常。

Is it a better way to grab a remote file and convert to a working base64? 这是获取远程文件并将其转换为可工作的base64的更好方法吗?

EDIT: The code bellow will NOT work with a remote image. 编辑:该代码波纹管将与远程图像工作。 Sorry, was running the Chrome with the '--disable-web-security' flag. 抱歉,正在运行带有“ --disable-web-security”标志的Chrome。

I have made a simple JsFiddle with a working version of what you want. 我用您想要的工作版本制作了一个简单的JsFiddle

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.
    return canvas.toDataURL("image/png");
}

var im = new Image();
im.onload = function(ev) {
    var im = ev.target;
    var img = document.getElementById("preview1");
    img.src = getBase64Image(im);
}
im.src = "http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG"

Oh, and I shamelessly copied the getBase64Image method from this other answer 哦,我从另一个答案中无耻地复制了getBase64Image方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM