Skip to main content

simple_image/
simple_image.rs

1//! Example: Convert an image to ASCII art using cascii as a library
2//! Run with: cargo run --example simple_image
3
4use cascii::{AsciiConverter, ConversionOptions};
5use std::path::Path;
6
7fn main() -> Result<(), Box<dyn std::error::Error>> {
8    // Create a converter with default configuration
9    let converter = AsciiConverter::new();
10
11    // Configure conversion options
12    let options = ConversionOptions::default()
13        .with_columns(100)
14        .with_font_ratio(0.5)
15        .with_luminance(20);
16
17    // Example 1: Convert image to ASCII file
18    let input = Path::new("resources/source.png");
19    let output = Path::new("example_output.txt");
20
21    if input.exists() {
22        println!("Converting {} to ASCII art...", input.display());
23        converter.convert_image(input, output, &options)?;
24        println!("✓ ASCII art saved to {}", output.display());
25    } else {
26        println!(
27            "Note: {} not found, skipping file conversion example",
28            input.display()
29        );
30    }
31
32    // Example 2: Convert image to string (no file)
33    if input.exists() {
34        println!("\nConverting image to string...");
35        let ascii_string = converter.image_to_string(input, &options)?;
36        println!(
37            "✓ Generated ASCII string ({} characters)",
38            ascii_string.len()
39        );
40        println!("\nFirst 500 characters:");
41        println!("{}", &ascii_string[..500.min(ascii_string.len())]);
42    }
43
44    // Example 3: Using presets
45    if input.exists() {
46        println!("\n\nUsing 'small' preset...");
47        let small_options = converter.options_from_preset("small")?;
48        let output_small = Path::new("example_output_small.txt");
49        converter.convert_image(input, output_small, &small_options)?;
50        println!("✓ Small ASCII art saved to {}", output_small.display());
51    }
52
53    Ok(())
54}