简体   繁体   中英

Javascript - Is it possible to base64 a remote image?

I have the following

HTML

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

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. Also when I paste the result (base64) as a url, it shows nothing.

When I use use input="file" and use FileReader() to get the file. it works fine.

Is it a better way to grab a remote file and convert to a working base64?

EDIT: The code bellow will NOT work with a remote image. Sorry, was running the Chrome with the '--disable-web-security' flag.

I have made a simple JsFiddle with a working version of what you want.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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