Volodymyr D.
Volodymyr D.

Reputation: 1382

HTML5 formdata: read image data from remote server

does someone know, is it possible read image to binary from remote URL. I know that File API give us possibility read as binary file from our local system. But i cant find info about reading from remote URL. Maybe even i can read this info from browser cache, after i load this info from to or else?

Upvotes: 0

Views: 1618

Answers (1)

Niels
Niels

Reputation: 49919

I think this will solve your problem, make a img tag with your url as SRC.

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

This function was found on Get image data in JavaScript?

Use it like

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

Or use your own img tag from your HTML

Upvotes: 1

Related Questions