Trying to write a function that can be exported so I can call on it in various places and easily pass it images.
I've tried various ways of incorporating the functions as async and using await wherever needed. Just don't seem to be getting it quite right. I have removed the attempted async/await functionality so you can see how the code looks beforehand.
const getPixels = require("get-pixels");
const imgLink = 'https://upload.wikimedia.org/wikipedia/commons/8/8a/LGBT_Rainbow_Flag.png';
exports.analyzeImg = imgLink => {
getPixels(imgLink, (err, pixels) => {
if (err) {
console.log("Bad image path");
return;
}
const copyPixelArr = [...pixels.data];
const rgbExtraction = grid => {
const allRed = [];
const allGreen = [];
const allBlue = [];
const allWhite = [];
for (let i = 0; i < grid.length; i += 4) {
allRed.push(grid[i]);
}
for (let i = 1; i < grid.length; i += 4) {
allGreen.push(grid[i]);
}
for (let i = 2; i < grid.length; i += 4) {
allBlue.push(grid[i]);
}
for (let i = 3; i < grid.length; i += 4) {
allWhite.push(grid[i]);
}
const avgRed =
allRed.reduce((acc, val) => {
acc += val;
return acc;
}, 0) / allRed.length;
const avgGreen =
allGreen.reduce((acc, val) => {
acc += val;
return acc;
}, 0) / allGreen.length;
const avgBlue =
allBlue.reduce((acc, val) => {
acc += val;
return acc;
}, 0) / allBlue.length;
const avgWhite =
allWhite.reduce((acc, val) => {
acc += val;
return acc;
}, 0) / allWhite.length;
return {
r: avgRed,
g: avgGreen,
b: avgBlue,
w: avgWhite
};
};
const data = rgbExtraction(copyPixelArr);
console.log(data);
return data;
});
};
Currently the console.log(data) returns what I want it too however the return data; is undefined as it's not waiting for the other functions to run before it tried to return.