1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
//! This crate provides [`symbolize`] function that allows you to convert raster images into their symbolic versions.
//! It supports scaling the [`symbolize`]d images as well as coloring them for terminals with RGB-support.
//!
//! [`SymbolizeResult`] is a wrapper that allows you to easy convert a result to [`Vec<String>`], [`Vec<u8>`] or [`String`]
//!
//! # Example usage:
//!
//! ```
//! use image::{imageops::FilterType};
//! use std::{process, error::Error};
//! use symbolize::{symbolize, ColorType};
//!
//! fn main() -> Result<(), Box<dyn Error>> {
//!     let result = symbolize(
//!         "./image.png",
//!         0.1,
//!         // Function will use these symbols for the main average colors.
//!         // If the image has the most white pixels, the first character from the vector will be used for them, and so on.
//!         &vec!['*', '#', '@', ' '],
//!         FilterType::Nearest,
//!         ColorType::Bw,
//!     );
//!
//!     match result {
//!         Err(e) => {
//!             eprintln!("{}", e);
//!             process::exit(1);
//!         }
//!         Ok(result) => {
//!             for line in Into::<Vec<String>>::into(result) {
//!                 println!("{}", line)
//!             }
//!         }
//!     }
//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@@@@@@@@@@@@@@@@@@@@@@^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//! ````

use std::{
    collections::{hash_map::Entry, HashMap},
    error::Error,
    io,
};

use crossterm::style::{style, Color, Stylize};
use image::{
    imageops::{resize, FilterType},
    open, ImageBuffer, Rgb,
};

/// Helper wrapper struct that provides some [`Into`] implementations for easier convertation
pub struct SymbolizeResult(Vec<String>);

impl Into<String> for SymbolizeResult {
    fn into(self) -> String {
        self.0.join("\n")
    }
}

impl Into<Vec<u8>> for SymbolizeResult {
    fn into(self) -> Vec<u8> {
        self.0.join("\n").into_bytes()
    }
}

impl Into<Vec<String>> for SymbolizeResult {
    fn into(self) -> Vec<String> {
        self.0
    }
}

/// Determines whether the image should use colors for the rgb terminal.
#[derive(Debug)]
pub enum ColorType {
    Bw,
    Rgb,
}

impl Into<ColorType> for bool {
    fn into(self) -> ColorType {
        if self == true {
            ColorType::Rgb
        } else {
            ColorType::Bw
        }
    }
}

/// Main function of this crate. Turns your raster image into it's symbolic representation.
pub fn symbolize(
    path: &str,
    scale: f32,
    symbols: &[char],
    filter_type: FilterType,
    color_type: ColorType,
) -> Result<SymbolizeResult, Box<dyn Error>> {
    let mut image = open(path)?.into_rgb8();
    image = resize(
        &image,
        (image.width() as f32 * scale) as u32,
        (image.height() as f32 * scale) as u32,
        filter_type,
    );
    let colors_to_use = get_most_used_colours_with_symbols(&image, symbols);

    let mut result = vec![];
    for row in image.rows() {
        let mut result_row = vec![];
        for pixel in row {
            let (symbol, average_pixel) = get_symbol_by_pixel(&colors_to_use, pixel)?;
            let str_symbol = match color_type {
                ColorType::Bw => symbol.to_string(),
                ColorType::Rgb => {
                    format!(
                        "{}",
                        style(symbol.to_string()).with(Color::from((
                            average_pixel.0[0],
                            average_pixel.0[1],
                            average_pixel.0[2]
                        )))
                    )
                }
            };
            result_row.push(str_symbol.clone());
            result_row.push(str_symbol);
        }

        result.push(result_row.join(""))
    }

    Ok(SymbolizeResult(result))
}

#[derive(Debug)]
struct PixelWithSymbol {
    pixel: Rgb<u8>,
    symbol: char,
}

impl PixelWithSymbol {
    fn new(pixel: Rgb<u8>, symbol: char) -> Self {
        Self { pixel, symbol }
    }
}

fn get_most_used_colours_with_symbols(
    image: &ImageBuffer<Rgb<u8>, Vec<u8>>,
    symbols: &[char],
) -> Vec<PixelWithSymbol> {
    let mut colors_uses: HashMap<&image::Rgb<u8>, usize> = HashMap::new();
    for pixel in image.pixels() {
        match colors_uses.entry(pixel) {
            Entry::Vacant(entry) => {
                entry.insert(1);
            }
            Entry::Occupied(mut entry) => {
                *entry.get_mut() += 1;
            }
        }
    }
    let mut colours_uses_vec: Vec<(&Rgb<u8>, usize)> = colors_uses.into_iter().collect();
    colours_uses_vec.sort_by_key(|(_, count)| *count);

    let (start, end) = (
        colours_uses_vec.len() - symbols.len(),
        colours_uses_vec.len(),
    );

    let mut symbol_idx = symbols.len() - 1;
    colours_uses_vec
        .drain(start..end)
        .map(|(pixel, _)| {
            let pixel_with_symbol = PixelWithSymbol::new(*pixel, symbols[symbol_idx]);
            symbol_idx = symbol_idx.checked_sub(1).unwrap_or(0);

            pixel_with_symbol
        })
        .collect()
}

fn get_symbol_by_pixel(
    pixels_with_info: &[PixelWithSymbol],
    pixel_to_compare: &Rgb<u8>,
) -> Result<(char, Rgb<u8>), io::Error> {
    let mut char = None;
    let mut rgb_pixel = None;
    let mut comparison = None;

    for PixelWithSymbol { pixel, symbol } in pixels_with_info {
        let pretendent_comparison = get_pixel_comparison(pixel_to_compare, pixel);
        if comparison.is_none() || pretendent_comparison < comparison.unwrap() {
            char = Some(*symbol);
            comparison = Some(pretendent_comparison);
            rgb_pixel = Some(*pixel);
        }
    }

    if let (Some(char), Some(rgb_pixel)) = (char, rgb_pixel) {
        return Ok((char, rgb_pixel));
    }

    Err(io::Error::new(
        io::ErrorKind::Other,
        "unexpected error, can't find matching char for a pixel. aborting",
    ))
}

fn get_pixel_comparison(first: &Rgb<u8>, second: &Rgb<u8>) -> usize {
    ((first.0[0] as i16 - second.0[0] as i16).abs()
        + (first.0[1] as i16 - second.0[1] as i16).abs()
        + (first.0[2] as i16 - second.0[2] as i16).abs()) as usize
}