Skip to content

Instantly share code, notes, and snippets.

@manzt
Last active September 23, 2024 20:11
Show Gist options
  • Save manzt/4742b4a73f1b1bb661ecd222a285d09c to your computer and use it in GitHub Desktop.
Save manzt/4742b4a73f1b1bb661ecd222a285d09c to your computer and use it in GitHub Desktop.
/**
* MIT License
*
* Copyright (c) 2024 Trevor Manz
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import * as cli from "jsr:@std/[email protected]";
import { Image } from "https://deno.land/x/[email protected]/mod.ts";
let ASCII_CHARS = " .:-=+*#%@" as const;
let CHAR_ASPECT_RATIO = 0.45 as const;
let BRIGHTNESS_THRESHOLD = 200 as const; // thresh whether image is bright
function getAsciiChar(
r: number,
g: number,
b: number,
invert: boolean,
): string {
let value = (r + g + b) / 3;
let index = Math.floor(value / 25.6);
return invert
? ASCII_CHARS[ASCII_CHARS.length - 1 - index]
: ASCII_CHARS[index];
}
function calcAverageBrightness(image: Image): number {
let totalBrightness = 0;
for (let y = 1; y <= image.height; y++) {
for (let x = 1; x <= image.width; x++) {
let [r, g, b] = image.getRGBAAt(x, y);
totalBrightness += (r + g + b) / 3;
}
}
let avgBrightness = totalBrightness / (image.width * image.height);
return avgBrightness;
}
async function imageToAscii(
path: string,
options: { width: number },
): Promise<string> {
let image = await Image.decode(await Deno.readFile(path));
let aspectRatio = image.width / image.height / CHAR_ASPECT_RATIO;
let out = image.resize(
options.width,
Math.floor(options.width / aspectRatio),
);
let invert = calcAverageBrightness(out) > BRIGHTNESS_THRESHOLD;
let text = "";
for (let y = 1; y <= out.height; y++) {
for (let x = 1; x <= out.width; x++) {
let [r, g, b] = out.getRGBAAt(x, y);
text += getAsciiChar(r, g, b, invert);
}
text += "\n";
}
return text;
}
if (import.meta.main) {
let args = cli.parseArgs(Deno.args, {
string: ["width"],
default: { width: "100" },
});
let path = args._[0];
let width = parseInt(args.width);
if (!path) {
console.error(
"Usage: deno run -R -N ascii-cat.ts <image-path> [--width <width>]",
);
Deno.exit(1);
}
try {
let text = await imageToAscii(String(path), { width });
Deno.stdout.writeSync(new TextEncoder().encode(text));
} catch (error) {
console.error("Error: " + error.message);
Deno.exit(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment