Skip to content

Instantly share code, notes, and snippets.

@josephrocca
Last active February 25, 2018 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephrocca/102acc005c801b0a3b0bf79bccc7532f to your computer and use it in GitHub Desktop.
Save josephrocca/102acc005c801b0a3b0bf79bccc7532f to your computer and use it in GitHub Desktop.
Get image data (pixel RGB array, width, height) by URL
// Only works for images hosted on the same domain unless CORs headers of image allow you to use it.
// Usage:
// let data = await getImageData("http://example.com/image.png");
// Put it in a try/catch to handle errors or use await getImageData("...").catch(e => ...);
function getImageData(url) {
return new Promise((resolve, reject) => {
let img = new Image();
img.onload = function() {
let canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
resolve( ctx.getImageData(0, 0, canvas.width, canvas.height) );
};
img.onerror = reject;
img.src = url;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment