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
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
679 changes: 610 additions & 69 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ edition = "2021"
[dependencies]
ansi_term = "0.12.1"
clap = { version = "4.3.0", features = [ "derive" ] }
image = "0.24.6"
image = "0.25.5"
unicode-segmentation = "1.10.1"


Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Options:
-w, --width <WIDTH> Width of the output image. Defaults to 128 if width and height are not specified
-H, --height <HEIGHT> Height of the output image, if not specified, it will be calculated to keep the aspect ratio
-c, --color Whether to use colors in the output image
-e, --escape-each-char Whether all characters should have an ANSI color code before each character. Defaults to only escape colored strings upon color change
-i, --invert Inverts the weights of the characters. Useful for white backgrounds
-C, --charset <CHARSET> Characters used to render the image, from transparent to opaque. Built-in charsets: block, emoji, default, russian, slight [default: default]
-h, --help Print help
Expand All @@ -39,7 +40,7 @@ Options:
> Your terminal emulator has to support `truecolor` (don't worry,
> almost all modern terminal emulators do).

- **Super efficient colored output**: RASCII never repeats the same ANSI color
- **Super efficient colored output**: RASCII (by default) never repeats the same ANSI color
code if it is already active.
> This makes a huge difference in images with little alternating color, up to
Stattek marked this conversation as resolved.
Show resolved Hide resolved
> about 1800% reduction in output size. Woah!
Expand Down
14 changes: 9 additions & 5 deletions src/charsets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ pub const CHINESE: &[&str] = &[
];
pub const DEFAULT: &[&str] = &[
" ", ".", "`", "^", "\"", "\\", ",", ":", ";", "I", "l", "!", "i", ">", "<", "~", "+", "_",
"-", "?", "]", "[", "}", "{", "1", ")", "(", "|", "\\", "/", "t", "f", "j", "r", "x", "n",
"u", "v", "c", "z", "X", "Y", "U", "J", "C", "L", "Q", "0", "O", "Z", "m", "w", "q", "p",
"d", "b", "k", "h", "a", "o", "*", "#", "M", "W", "&", "8", "%", "B", "$", "@",
"-", "?", "]", "[", "}", "{", "1", ")", "(", "|", "\\", "/", "t", "f", "j", "r", "x", "n", "u",
"v", "c", "z", "X", "Y", "U", "J", "C", "L", "Q", "0", "O", "Z", "m", "w", "q", "p", "d", "b",
"k", "h", "a", "o", "*", "#", "M", "W", "&", "8", "%", "B", "$", "@",
];
pub const EMOJI: &[&str] = &[
"\u{3000}", "\u{3000}", "。", ",", "🧔", "👶", "🗣", "👥", "👤", "👀", "👁", "🦴", "🦷", "🫁",
Expand All @@ -22,8 +22,11 @@ pub const RUSSIAN: &[&str] = &[
"О", "Н", "М", "Л", "К", "Й", "И", "З", "Ж", "Ё", "Е", "Д", "Г", "В", "Б", "А",
];
pub const SLIGHT: &[&str] = &[
" ", " ", ".", "`", "\"", "\\", ":", "I", "!", ">", "~", "_", "?", "[", "{", "|", ")", "(",
"\\", "\\\\", "/", "Y", "L", "p", "d", "a", "*", "W", "8", "%", "@", "$",
" ", ".", "`", "\"", "\\", ":", "I", "!", ">", "~", "_", "?", "[", "{", "|", ")", "(", "\\",
"\\\\", "/", "Y", "L", "p", "d", "a", "*", "W", "8", "%", "@", "$",
];
pub const MINIMAL: &[&str] = &[
" ", " ", ".", ":", "'", ";", "o", "l", "d", "c", "x", "0", "k", "K", "N", "M", "W", "X",
];

pub fn from_str(s: &str) -> Option<&[&str]> {
Expand All @@ -34,6 +37,7 @@ pub fn from_str(s: &str) -> Option<&[&str]> {
"emoji" => Some(EMOJI),
"russian" => Some(RUSSIAN),
"slight" => Some(SLIGHT),
"minimal" => Some(MINIMAL),
_ => None,
}
}
1 change: 1 addition & 0 deletions src/gif_renderer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

40 changes: 20 additions & 20 deletions src/image_renderer.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
use std::io;
use std::{io, u8};

use ansi_term::Color;
use image::{
DynamicImage,
Rgba,
};
use image::{DynamicImage, Rgba};

use super::renderer::{
RenderOptions,
Renderer,
};
use super::renderer::{RenderOptions, Renderer};

pub struct ImageRenderer<'a> {
resource: &'a DynamicImage,
Expand All @@ -19,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 percent_opaque = self.get_opacity_percent(pixel);
Stattek marked this conversation as resolved.
Show resolved Hide resolved

// 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 percent_opaque < 0.95 {
// if we are below 95% opacity, 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 @@ -30,6 +29,10 @@ impl ImageRenderer<'_> {
}]
}

fn get_opacity_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 Expand Up @@ -88,7 +91,8 @@ impl<'a> Renderer<'a, DynamicImage> for ImageRenderer<'a> {
if self.options.colored {
let color = Color::RGB(pixel[0], pixel[1], pixel[2]);

if last_color != Some(color) {
// write prefix before a new color, unless we escape all characters individually
if self.options.escape_each_colored_char || last_color != Some(color) {
write!(writer, "{}", color.prefix())?;
}

Expand All @@ -111,7 +115,6 @@ impl<'a> Renderer<'a, DynamicImage> for ImageRenderer<'a> {
fn render(&self, buffer: &mut String) -> io::Result<()> {
let (width, height) = (
self.options.width.unwrap_or_else(|| {

(self
.options
.height
Expand All @@ -122,7 +125,6 @@ impl<'a> Renderer<'a, DynamicImage> for ImageRenderer<'a> {
* 2.0)
.ceil() as u32
}),

self.options.height.unwrap_or_else(|| {
(self
.options
Expand All @@ -134,7 +136,6 @@ impl<'a> Renderer<'a, DynamicImage> for ImageRenderer<'a> {
/ 2.0)
.ceil() as u32
}),

);

let image = self.resource.thumbnail_exact(width, height).to_rgba8();
Expand All @@ -150,7 +151,7 @@ impl<'a> Renderer<'a, DynamicImage> for ImageRenderer<'a> {

if let Some(last_color_value) = last_color {
buffer.push_str(&last_color_value.suffix().to_string()); // TODO look up for a
// better solution after benchmarking.
// better solution after benchmarking.
last_color = None;
}

Expand All @@ -160,7 +161,8 @@ impl<'a> Renderer<'a, DynamicImage> for ImageRenderer<'a> {
if self.options.colored {
let color = Color::RGB(pixel[0], pixel[1], pixel[2]);

if last_color != Some(color) {
// write prefix before a new color, unless we escape all characters individually
if self.options.escape_each_colored_char || last_color != Some(color) {
buffer.push_str(&color.prefix().to_string());
}

Expand All @@ -173,13 +175,11 @@ impl<'a> Renderer<'a, DynamicImage> for ImageRenderer<'a> {
buffer.push_str(char_for_pixel);
}


if let Some(last_color) = last_color {
buffer.push_str(&last_color.suffix().to_string()); // TODO look up for a
// better solution after benchmarking.
// better solution after benchmarking.
}

Ok(())
}

}
13 changes: 8 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
use std::io;

use clap::Parser;
use rascii_art::{
charsets,
RenderOptions,
};
use rascii_art::{charsets, RenderOptions};
use unicode_segmentation::UnicodeSegmentation;

#[derive(Debug, Parser)]
Expand All @@ -27,6 +24,11 @@ struct Args {
#[arg(name = "color", short, long)]
colored: bool,

/// Whether all characters should have an ANSI color code before each character.
/// Defaults to only escape colored strings upon color change.
#[arg(name = "escape-each-char", short, long)]
escape_each_colored_char: bool,

/// Inverts the weights of the characters. Useful for white backgrounds
#[arg(short, long)]
invert: bool,
Expand All @@ -44,7 +46,7 @@ fn main() -> image::ImageResult<()> {
let charset = charsets::from_str(args.charset.as_str()).unwrap_or(clusters.as_slice());

if args.width.is_none() && args.height.is_none() {
args.width = Some(80);
args.width = Some(128);
}

rascii_art::render(
Expand All @@ -55,6 +57,7 @@ fn main() -> image::ImageResult<()> {
height: args.height,
colored: args.colored,
invert: args.invert,
escape_each_colored_char: args.escape_each_colored_char,
charset,
},
)?;
Expand Down
8 changes: 8 additions & 0 deletions src/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub struct RenderOptions<'a> {
pub width: Option<u32>,
pub height: Option<u32>,
pub colored: bool,
pub escape_each_colored_char: bool,
pub invert: bool,
pub charset: &'a [&'a str],
}
Expand Down Expand Up @@ -38,6 +39,12 @@ impl<'a> RenderOptions<'a> {
self
}

/// Set whether each colored char should be escaped in the rendered image.
pub fn escape_each_colored_char(mut self, escape_each_colored_char: bool) -> Self {
self.escape_each_colored_char = escape_each_colored_char;
self
}

/// Set whether the rendered image charset should be inverted.
pub fn invert(mut self, invert: bool) -> Self {
self.invert = invert;
Expand All @@ -57,6 +64,7 @@ impl Default for RenderOptions<'_> {
width: None,
height: None,
colored: false,
escape_each_colored_char: false,
invert: false,
charset: charsets::DEFAULT,
}
Expand Down