Skip to content

Instantly share code, notes, and snippets.

@nubilfi
Created December 3, 2023 08:50
Show Gist options
  • Save nubilfi/0d36647fdb4bbf7d712af92379276ebf to your computer and use it in GitHub Desktop.
Save nubilfi/0d36647fdb4bbf7d712af92379276ebf to your computer and use it in GitHub Desktop.
Rust Image URL to ASCII
use image::{io::Reader as ImageReader, GenericImageView};
use reqwest::blocking::get;
use std::io::{Cursor, Write};
fn main() {
// Fetch the image from the URL
let url = "https://media-4.api-sports.io/football/teams/529.png";
let response = get(url).expect("Failed to fetch the image");
let bytes = response.bytes().expect("Failed to read response bytes");
// Create a cursor from the response bytes
let cursor = Cursor::new(bytes);
// Convert the cursor to a dynamic image
let img = ImageReader::with_format(cursor, image::ImageFormat::Png)
.decode()
.expect("Failed to decode image");
// Convert the image to an ascii
let glyph = convert_image_to_ascii(&img);
// Simulating appending ascii to the output using write!()
let mut output = Vec::new();
write!(&mut output, "{}", glyph).expect("Failed to write to output");
// Print the output (or use it as needed)
println!("{}", String::from_utf8_lossy(&output));
}
fn convert_image_to_ascii(img: &image::DynamicImage) -> String {
// Resize the image to a specific width and height
let resized_img = img.resize_exact(90, 50, image::imageops::FilterType::Lanczos3);
// Convert the resized image to grayscale
let grayscale_img = resized_img.grayscale();
// Define the ASCII characters to represent varying intensities
let ascii_chars = ['0', '#', '8', '&', 'o', ':', '*', '.', ' '];
let mut result = String::new();
// Iterate through each pixel and convert its intensity to ASCII
for y in 0..grayscale_img.height() {
for x in 0..grayscale_img.width() {
let pixel = grayscale_img.get_pixel(x, y);
let luminance = pixel[0] as usize; // Assuming grayscale has only one channel
// Normalize luminance to ASCII characters
let index = (luminance * (ascii_chars.len() - 1)) / 255;
let ascii_char = ascii_chars[index];
result.push(ascii_char);
}
result.push('\n'); // Newline for each row
}
result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment