Sunday, August 4, 2013

Image Data URIs with JavaScript

<img src="your_image.png" id="myimage" />
<canvas width="300" height="300" id="mycanvas" style="display: none;"></canvas>


You will need to create a canvas element with the correct dimensions and copy the image data with thedrawImage function. Then you can use the toDataURL function to get a data: url that has the base-64 encoded image. Note that the image must be fully loaded, or you'll just get back an empty (black, transparent) image.
It would be something like this. I've never written a Greasemonkey script, so you might need to adjust the code to run in that environment.
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);

    var dataURL = canvas.toDataURL();

    return dataURL;
}
var myImage = document.getElementById('myimage');
var imageData = getbase64Image(myImage);
Return like something: "data:image/png;base64,BASE_64_IMAGE_DATA"; 

No comments:

Post a Comment