Skip to content

Instantly share code, notes, and snippets.

@gamesbrainiac
Last active May 22, 2024 20:09
Show Gist options
  • Save gamesbrainiac/8dd39d5617e6ff78a63d22064bde8f84 to your computer and use it in GitHub Desktop.
Save gamesbrainiac/8dd39d5617e6ff78a63d22064bde8f84 to your computer and use it in GitHub Desktop.
ASCII Art Generator Rust
use image::{DynamicImage, GrayImage};
use std::path::Path;
struct ASCIIArtGeneratorRust {
ascii_chars: Vec<char>,
}
impl ASCIIArtGeneratorRust {
/// Constructs a new ASCIIArtGenerator with a given set of ASCII characters.
fn new(ascii_chars: &str) -> Self {
// Initialize the ascii_chars vector from the provided string.
}
/// Scales the image to a specified width while maintaining aspect ratio.
/// Returns the scaled and converted grayscale image.
fn scale_image(&self, image: &DynamicImage, new_width: u32) -> GrayImage {
// Calculate the new height based on the aspect ratio.
// Resize the image to these new dimensions.
// The last part is tricky and requires library knowledge.
image.resize_exact(new_width, new_height, image::imageops::FilterType::Nearest).to_luma8()
}
/// Converts the grayscale image pixels to ASCII characters.
/// Returns a string where each pixel's brightness is represented by a specific ASCII character.
fn map_pixels_to_ascii(&self, image: &GrayImage) -> String {
// Get the image height
// Get the image width
// Create a new string, that will be used to concatenate all
// the pixel to character transformations.
// Get the length of the ascii characters offered,
// So that they can be used to map to intensity.
for y in 0..height {
for x in 0..width {
let pixel = image.get_pixel(x, y);
let intensity = pixel.0[0];
let index = (intensity as u32 * ascii_len / 256) as usize;
ascii_art.push(self.ascii_chars[index]);
}
ascii_art.push('\n'); // Add newline after each row
}
ascii_art
}
/// Generates ASCII art from the specified image path.
/// Returns the ASCII art as a string.
fn generate_ascii_art(&self, image_path: &Path, width: u32) -> String {
// Open the image file from the specified path.
// Scale the image to the desired width and convert it to grayscale.
// Map the grayscale pixels to ASCII characters.
// Return the generated ASCII art string.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment