+ 1

Is there a way for JavaScript, to take a image as input(in png,etc)and convert that to a data type(e.g. 2D ARRAY)

Actually, what i mean is this I take the image file in. And convert all the pixels sequentially into (r,g,b) format or something similar, and store it in a array. Otherwise stated, i just want to process a image, which is taken in as file😢

21st Apr 2020, 8:03 AM
Omkar Bhale
Omkar Bhale - avatar
3 Antworten
+ 2
Omkar Bhale You can also create the image in memory yes. const img = new Image(); img.src = 'cute_cats.jpg'; img.onload = () => { ctx.drawImage(img, 0, 0); ... }; I usually like to wrap this code in a promise: const image = source => new Promise(resolve => { const img = new Image(); img.src = source; img.onload = () => resolve(img); }); Then you can const img = await image('cute_cats.jpg'); ctx.drawImage(img, 0, 0); Alternatively you can even grab a file via `request` or `XMLHttpRequest` and not use the `Image` constructor at all.
21st Apr 2020, 10:35 AM
Schindlabua
Schindlabua - avatar
+ 2
Yep! You can put the image on a canvas: const img = document.getElementById("abc"); const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); The image needs to be fully loaded for this. Check `image.onload` if necessary. Once you have the canvas you can read it's array of pixels. const pd = ctx.getImageData(0, 0, width, height); And now you have an array-like (a Uint8ClampedArray) inside `pd.data` that looks like pd.data; // [r,g,b,a,r,g,b,a,...] (where a is the alpha channel, i.e. transparency.)
21st Apr 2020, 10:25 AM
Schindlabua
Schindlabua - avatar
+ 2
Schindlabua Got it. Thanks for your answer. Just one thing, can we do it without drawing anything on the DOM.
21st Apr 2020, 10:28 AM
Omkar Bhale
Omkar Bhale - avatar