Reduce grayscale alpha to palette

This commit is contained in:
Andrew 2022-12-04 17:30:34 +13:00 committed by Josh Holmer
parent 38c26440e6
commit 43d0ee8807
2 changed files with 16 additions and 5 deletions

View file

@ -3,7 +3,7 @@ use crate::headers::IhdrData;
use crate::png::PngImage; use crate::png::PngImage;
use indexmap::IndexMap; use indexmap::IndexMap;
use itertools::Itertools; use itertools::Itertools;
use rgb::{FromSlice, RGB8, RGBA8}; use rgb::{FromSlice, RGB8, RGBA, RGBA8};
use rustc_hash::FxHasher; use rustc_hash::FxHasher;
use std::hash::{BuildHasherDefault, Hash}; use std::hash::{BuildHasherDefault, Hash};
@ -105,7 +105,7 @@ where
} }
#[must_use] #[must_use]
pub fn reduced_color_to_palette(png: &PngImage) -> Option<PngImage> { pub fn reduce_to_palette(png: &PngImage) -> Option<PngImage> {
if png.ihdr.bit_depth != BitDepth::Eight { if png.ihdr.bit_depth != BitDepth::Eight {
return None; return None;
} }
@ -131,6 +131,17 @@ pub fn reduced_color_to_palette(png: &PngImage) -> Option<PngImage> {
&mut palette, &mut palette,
&mut raw_data, &mut raw_data,
) )
} else if png.ihdr.color_type == ColorType::GrayscaleAlpha {
reduce_scanline_to_palette(
line.data.as_gray_alpha().iter().cloned().map(|px| RGBA {
r: px.0,
g: px.0,
b: px.0,
a: px.1,
}),
&mut palette,
&mut raw_data,
)
} else { } else {
debug_assert_eq!(png.ihdr.color_type, ColorType::RGBA); debug_assert_eq!(png.ihdr.color_type, ColorType::RGBA);
reduce_scanline_to_palette( reduce_scanline_to_palette(

View file

@ -206,14 +206,14 @@ pub fn reduce_color_type(png: &PngImage, grayscale_reduction: bool) -> Option<Pn
.or_else(|| reduced_alpha_channel(&reduced)) .or_else(|| reduced_alpha_channel(&reduced))
{ {
reduced = Cow::Owned(r); reduced = Cow::Owned(r);
} else if let Some(r) = reduced_color_to_palette(&reduced) { } else if let Some(r) = reduce_to_palette(&reduced) {
reduced = Cow::Owned(r); reduced = Cow::Owned(r);
should_reduce_bit_depth = true; should_reduce_bit_depth = true;
} }
} }
if reduced.ihdr.color_type == ColorType::GrayscaleAlpha { if reduced.ihdr.color_type == ColorType::GrayscaleAlpha {
if let Some(r) = reduced_alpha_channel(&reduced) { if let Some(r) = reduced_alpha_channel(&reduced).or_else(|| reduce_to_palette(&reduced)) {
reduced = Cow::Owned(r); reduced = Cow::Owned(r);
should_reduce_bit_depth = true; should_reduce_bit_depth = true;
} }
@ -225,7 +225,7 @@ pub fn reduce_color_type(png: &PngImage, grayscale_reduction: bool) -> Option<Pn
} else { } else {
None None
} }
.or_else(|| reduced_color_to_palette(&reduced)) .or_else(|| reduce_to_palette(&reduced))
{ {
reduced = Cow::Owned(r); reduced = Cow::Owned(r);
should_reduce_bit_depth = true; should_reduce_bit_depth = true;