Skip to content

Commit 8a8c5d6

Browse files
committed
Invert image when bpp == 1
1 parent 47b71d0 commit 8a8c5d6

File tree

1 file changed

+17
-26
lines changed

1 file changed

+17
-26
lines changed

include_gif/src/lib.rs

Lines changed: 17 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ extern crate proc_macro;
22

33
use image::*;
44
use proc_macro::TokenStream;
5-
use std::collections::HashMap;
65
use std::io::Write;
76
use syn::{parse_macro_input, Ident, LitStr};
87

@@ -154,33 +153,25 @@ fn generate_bagl_glyph(frame: &GrayImage) -> Vec<u8> {
154153
packed
155154
}
156155

157-
// Get the palette of colors of a grayscale image
158-
fn get_palette<'a>(img: &'a GrayImage) -> Vec<u8> {
159-
let mut palette = HashMap::new();
160-
// Count the number of occurrences of each color
161-
for &pixel in img.pixels() {
162-
*palette.entry(pixel[0]).or_insert(0) += 1;
156+
fn image_to_packed_buffer(frame: &mut GrayImage) -> (Vec<u8>, u8) {
157+
// Count the number of colors in the image (max 16 supported)
158+
let mut color_count = std::collections::HashSet::new();
159+
for pixel in frame.pixels() {
160+
color_count.insert(pixel.0[0]);
163161
}
164-
let palette: Vec<_> = palette.into_iter().collect();
165-
// Collect all colors in a vector
166-
palette.into_iter().map(|(luma, _)| luma).collect()
167-
}
162+
let mut colors = std::cmp::max(16u8, color_count.len() as u8);
168163

169-
fn image_to_packed_buffer(frame: &GrayImage) -> (Vec<u8>, u8) {
170-
let mut colors = get_palette(&frame).len() as u8;
171-
if colors > 16 {
172-
colors = 16;
173-
}
174164
// Round number of colors to a power of 2
175-
if !(colors != 0 && colors.count_ones() == 1) {
176-
colors = (2.0_f64.powf((colors as f64).log2().ceil())) as u8;
177-
}
165+
colors = colors.next_power_of_two();
178166

179-
let mut bits_per_pixel: u8 = (colors as f32).log2().floor() as u8;
180-
match bits_per_pixel {
181-
0 => bits_per_pixel = 1,
182-
3 => bits_per_pixel = 4,
183-
_ => (),
167+
// Compute number of bits per pixel from number of colors
168+
let bits_per_pixel = (colors as f64).log(2.0).ceil() as u8;
169+
170+
// Invert if bpp is 1
171+
if bits_per_pixel == 1 {
172+
for pixel in frame.pixels_mut() {
173+
pixel.0[0] = 255 - pixel.0[0];
174+
}
184175
}
185176

186177
let width = frame.width();
@@ -224,10 +215,10 @@ fn generate_nbgl_glyph(frame: &mut GrayImage) -> (Vec<u8>, u8, bool) {
224215
*pixel = Luma([0; 1]);
225216
}
226217
});
227-
let (packed, bpp) = image_to_packed_buffer(&frame);
218+
let (packed, bpp) = image_to_packed_buffer(frame);
228219
return (packed, bpp, false);
229220
}
230-
let (packed, bpp) = image_to_packed_buffer(&frame);
221+
let (packed, bpp) = image_to_packed_buffer(frame);
231222
let mut compressed_image: Vec<u8> = Vec::new();
232223
let mut full_uncompressed_size = packed.len();
233224
let mut i = 0;

0 commit comments

Comments
 (0)