bitfont/bitfont.js

48 lines
1.7 KiB
JavaScript

const Jimp = require("jimp");
const prompt = require("prompt");
const sizeOf = require("image-size");
const fs = require("node:fs");
const file = process.argv[2];
const charWidth = parseInt(process.argv[3]) || 8;
const charHeight = parseInt(process.argv[4]) || 8;
const dimensions = sizeOf(file);
const imgWidth = dimensions.width;
const imgHeight = dimensions.height;
Jimp.read(file, async (_err, img) => {
let charArray = [];
let row;
let buffer = ``;
prompt.start();
const { fontName } = await prompt.get({name: 'fontName', description: 'Font Name', hidden: false, type: 'string', default: 'My Bitsy Font'});
buffer += `FONT ${fontName}\n`;
buffer += `SIZE ${charWidth} ${charHeight}\n`;
for (let y = 0; y < imgHeight; y += 1) {
row = [];
for (let x = 0; x < imgWidth; x += 1) {
row.push(img.getPixelColor(x, y) == 255 ? 1 : 0);
}
charArray.push(row);
}
let character;
for (y = 0; y < imgHeight; y += charHeight) {
for (x = 0; x < imgWidth; x += charWidth) {
character = charArray.slice(y, y + charHeight).map(line => line.slice(x, x + charWidth).join(""));
character.forEach((line) => console.log(line.replace(/1/g, "\x1b[30m1\x1b[0m")));
let { code } = await prompt.get({name: 'code', description: 'Character Code', hidden: false, type: 'string', required: true});
buffer += `\nCHAR ${code}\n`;
buffer += character.join("\n");
}
}
const { path } = await prompt.get({name: 'path', description: 'Path to Write', hidden: false, type: 'string', default: 'my_bitsy_font.bitsyfont'});
fs.writeFile(path, buffer, (err) => {
if (err) {
console.error(err);
} else {
console.log(`Font written to ${path}!`);
}
});
});