Created
February 4, 2023 21:11
-
-
Save juliarose/ee2faa40e3b43d5b6dfcdbebe270d7bc to your computer and use it in GitHub Desktop.
This file contains 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
const getPixels = require("get-pixels"); | |
const fs = require('fs'); | |
const { promisify } = require('util'); | |
const readFile = promisify(fs.readFile); | |
const path = require('path'); | |
async function getPixelsForImage(imagePath) { | |
return new Promise((resolve, reject) => { | |
getPixels(imagePath, (error, pixels) => { | |
if (error) { | |
return reject(error); | |
} | |
const matrix = []; | |
for (let y = 0; y < pixels.shape[1]; y++) { | |
const row = []; | |
for (let x = 0; x < pixels.shape[0]; x++) { | |
const r = pixels.get(x, y, 0); | |
const g = pixels.get(x, y, 1); | |
const b = pixels.get(x, y, 2); | |
const a = pixels.get(x, y, 3); | |
row.push({ | |
r, | |
g, | |
b, | |
a | |
}); | |
} | |
matrix.push(row); | |
} | |
return resolve(matrix); | |
}) | |
}); | |
} | |
(async function() { | |
const dir = './temp'; | |
const files = fs.readdirSync('./temp') | |
.sort((a, b) => { | |
a = parseInt(a.match(/(\d+)/, a)[1]); | |
b = parseInt(b.match(/(\d+)/, b)[1]); | |
return a - b; | |
}); | |
let s = '[\n'; | |
console.log(files); | |
for (let i = 0; i < files.length; i++) { | |
let imagePath = files[i]; | |
let filePath = path.join(dir, imagePath); | |
let pixels = await getPixelsForImage(filePath); | |
s += '[\n'; | |
for (let i = 0; i < pixels.length; i++) { | |
s += '[ '; | |
for (let j = 0; j < pixels[i].length; j++) { | |
let pixel = pixels[i][j]; | |
let { r, g, b } = pixel; | |
s += `(${r}, ${g}, ${b}), `; | |
} | |
s += '],\n'; | |
} | |
s += '],\n'; | |
} | |
s += '];'; | |
console.log(s); | |
fs.writeFileSync('pixels.rs', s, 'utf8'); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment