Last active
February 25, 2018 06:04
-
-
Save josephrocca/102acc005c801b0a3b0bf79bccc7532f to your computer and use it in GitHub Desktop.
Get image data (pixel RGB array, width, height) by URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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