Skip to main content

muscii/
lib.rs

1use anyhow::Result;
2use clap::Parser;
3use image::{imageops::FilterType, GenericImageView, Pixel};
4use std::path::PathBuf;
5
6use crossterm::{
7	execute,
8	style::{Color, Print, ResetColor, SetForegroundColor},
9};
10use std::io::{stdout, Write};
11
12/// Command-line tool that displays images as colorized ASCII art in the terminal.
13#[derive(Parser, Debug)]
14#[command(version, about, long_about = None)]
15struct Cli {
16	#[arg(required = true)]
17	path: PathBuf,
18
19	#[arg(short = 'w', long = "width")]
20	width: Option<usize>,
21
22	#[arg(short = 'H', long = "height")]
23	height: Option<usize>,
24}
25
26const DEFAULT_WIDTH: u32 = 64;
27const FONT_ASPECT_RATIO: f64 = 2.0;
28const ASCII_RAMP: &str = r#" .-=+*x#$&X@"#;
29
30/// Compute target character dimensions from optional width/height and image aspect.
31fn calculate_target_dimensions(
32	width_opt: Option<usize>,
33	height_opt: Option<usize>,
34	original_width: u32,
35	original_height: u32,
36) -> (u32, u32) {
37	let img_aspect = original_height as f64 / original_width as f64;
38
39	match (width_opt, height_opt) {
40		(Some(w), Some(h)) => (w as u32, h as u32),
41		(Some(w), None) => {
42			let h = (w as f64 * img_aspect / FONT_ASPECT_RATIO).round() as u32;
43			(w as u32, h)
44		}
45		(None, Some(h)) => {
46			let w = (h as f64 * FONT_ASPECT_RATIO / img_aspect).round() as u32;
47			(w, h as u32)
48		}
49		(None, None) => {
50			let h = (DEFAULT_WIDTH as f64 * img_aspect / FONT_ASPECT_RATIO).round() as u32;
51			(DEFAULT_WIDTH, h)
52		}
53	}
54}
55
56/// Map grayscale luma (0..=255) to a character from the ramp.
57fn luma_to_ascii_char(luma: u8, ramp: &str) -> char {
58	let ramp_count = ramp.chars().count();
59	if ramp_count == 0 {
60		return ' ';
61	}
62	let last_index = ramp_count.saturating_sub(1) as f64;
63	let normalized = (luma as f64) / 255.0;
64	let idx = (normalized * last_index).round() as usize;
65	ramp.chars().nth(idx).unwrap_or_else(|| ramp.chars().next().unwrap_or(' '))
66}
67
68pub fn run() -> Result<()> {
69	let cli = Cli::parse();
70
71	let source_image = image::open(&cli.path)?;
72	let (orig_width, orig_height) = source_image.dimensions();
73
74	let (target_width, target_height) =
75		calculate_target_dimensions(cli.width, cli.height, orig_width, orig_height);
76
77	let resized = source_image.resize_exact(target_width, target_height, FilterType::Triangle);
78	let (cols, rows) = resized.dimensions();
79
80	let mut out = stdout();
81
82	for y in 0..rows {
83		for x in 0..cols {
84			let pixel = resized.get_pixel(x, y);
85			let r = pixel[0];
86			let g = pixel[1];
87			let b = pixel[2];
88			let luma = pixel.to_luma()[0];
89
90			let ch = luma_to_ascii_char(luma, ASCII_RAMP);
91			let fg_color = Color::Rgb { r, g, b };
92
93			execute!(out, SetForegroundColor(fg_color), Print(ch))?;
94		}
95		execute!(out, Print('\n'), ResetColor)?;
96		out.flush().ok();
97	}
98
99	Ok(())
100}