Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Transparent Pixel Support and Minor Fixes. #22

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
Open
2 changes: 1 addition & 1 deletion src/charsets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub const SLIGHT: &[&str] = &[
"\\\\", "/", "Y", "L", "p", "d", "a", "*", "W", "8", "%", "@", "$",
];
pub const MINIMAL: &[&str] = &[
" ", " ", ".", ":", "'", ";", "o", "l", "d", "c", "x", "0", "k", "K", "N", "M","W", "X",
" ", " ", ".", ":", "'", ";", "o", "l", "d", "c", "x", "0", "k", "K", "N", "M", "W", "X",
];

pub fn from_str(s: &str) -> Option<&[&str]> {
Expand Down
15 changes: 12 additions & 3 deletions src/image_renderer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::io;
use std::{io, u8};

use ansi_term::Color;
use image::{DynamicImage, Rgba};
Expand All @@ -13,9 +13,14 @@ pub struct ImageRenderer<'a> {
impl ImageRenderer<'_> {
fn get_char_for_pixel(&self, pixel: &Rgba<u8>, maximum: f64) -> &str {
let as_grayscale = self.get_grayscale(pixel) / maximum;
let transparency_percent = self.get_transparency_percent(pixel);

// TODO: Use alpha channel to determine if pixel is transparent?
let char_index = (as_grayscale * (self.options.charset.len() as f64 - 1.0)) as usize;
let char_index = if transparency_percent < 0.95 {
// if we have at least 95% transparency, count this pixel as transparent and give minimum index
0
} else {
(as_grayscale * (self.options.charset.len() as f64 - 1.0)) as usize
};

self.options.charset[if self.options.invert {
self.options.charset.len() - 1 - char_index
Expand All @@ -24,6 +29,10 @@ impl ImageRenderer<'_> {
}]
}

fn get_transparency_percent(&self, pixel: &Rgba<u8>) -> f64 {
pixel[3] as f64 / u8::MAX as f64
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

using u8::MAX is smarter than plain 255.

Just a note to myself

}

fn get_grayscale(&self, pixel: &Rgba<u8>) -> f64 {
((pixel[0] as f64 * 0.299) + (pixel[1] as f64 * 0.587) + (pixel[2] as f64 * 0.114)) / 255.0
}
Expand Down