Prevent conversion from grayscale when disabled

This commit is contained in:
Andrew 2023-05-30 08:16:33 +12:00 committed by Josh Holmer
parent 86fccf082a
commit c71fd44454
4 changed files with 16 additions and 5 deletions

View file

@ -229,7 +229,7 @@ fn reductions_rgba_to_palette_8(b: &mut Bencher) {
let input = test::black_box(PathBuf::from("tests/files/rgba_8_should_be_palette_8.png"));
let png = PngData::new(&input, &Options::default()).unwrap();
b.iter(|| color::reduced_to_indexed(&png.raw));
b.iter(|| color::reduced_to_indexed(&png.raw, true));
}
#[bench]
@ -237,7 +237,7 @@ fn reductions_rgb_to_palette_8(b: &mut Bencher) {
let input = test::black_box(PathBuf::from("tests/files/rgb_8_should_be_palette_8.png"));
let png = PngData::new(&input, &Options::default()).unwrap();
b.iter(|| color::reduced_to_indexed(&png.raw));
b.iter(|| color::reduced_to_indexed(&png.raw, true));
}
#[bench]
@ -247,7 +247,7 @@ fn reductions_grayscale_8_to_palette_8(b: &mut Bencher) {
));
let png = PngData::new(&input, &Options::default()).unwrap();
b.iter(|| color::reduced_to_indexed(&png.raw));
b.iter(|| color::reduced_to_indexed(&png.raw, true));
}
#[bench]

View file

@ -70,6 +70,14 @@ impl ColorType {
matches!(self, ColorType::RGB { .. } | ColorType::RGBA)
}
#[inline]
pub(crate) fn is_gray(&self) -> bool {
matches!(
self,
ColorType::Grayscale { .. } | ColorType::GrayscaleAlpha
)
}
#[inline]
pub(crate) fn has_alpha(&self) -> bool {
matches!(self, ColorType::GrayscaleAlpha | ColorType::RGBA)

View file

@ -32,13 +32,16 @@ where
}
#[must_use]
pub fn reduced_to_indexed(png: &PngImage) -> Option<PngImage> {
pub fn reduced_to_indexed(png: &PngImage, allow_grayscale: bool) -> Option<PngImage> {
if png.ihdr.bit_depth != BitDepth::Eight {
return None;
}
if matches!(png.ihdr.color_type, ColorType::Indexed { .. }) {
return None;
}
if !allow_grayscale && png.ihdr.color_type.is_gray() {
return None;
}
let mut raw_data = Vec::with_capacity(png.data.len() / png.channels_per_pixel());
let palette: Vec<_> = match png.ihdr.color_type {

View file

@ -108,7 +108,7 @@ pub(crate) fn perform_reductions(
// Attempt to reduce to indexed
let mut indexed = None;
if opts.color_type_reduction && !deadline.passed() {
if let Some(reduced) = reduced_to_indexed(&png) {
if let Some(reduced) = reduced_to_indexed(&png, opts.grayscale_reduction) {
// Make sure the palette gets sorted (but don't bother evaluating both results)
let new = Arc::new(sorted_palette(&reduced).unwrap_or(reduced));
// For relatively small differences, enter this into the evaluator