Skip to content

Instantly share code, notes, and snippets.

@KennyRedman
Created June 4, 2014 18:27
Show Gist options
  • Save KennyRedman/019ed6b2e8b7ec5d665f to your computer and use it in GitHub Desktop.
Save KennyRedman/019ed6b2e8b7ec5d665f to your computer and use it in GitHub Desktop.
Get image data in JavaScript?
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,/, "");
}
http://stackoverflow.com/questions/934012/get-image-data-in-javascript
You will need to create a canvas element with the correct dimensions and copy the image data with the drawImage 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.
Getting a JPEG-formatted image doesn't work on older versions (around 3.5) of Firefox, so if you want to support that, you'll need to check the compatibility. If the encoding is not supported, it will default to "image/png".
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment