From 417c6f0080ca3af0e259535f28040374cbf8bd48 Mon Sep 17 00:00:00 2001 From: lisyarus Date: Sun, 5 Feb 2023 00:33:53 +0300 Subject: [PATCH] Support more PNG color types --- libs/gfx/source/png.cpp | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/libs/gfx/source/png.cpp b/libs/gfx/source/png.cpp index 76bd5dcd..24d6c9f9 100644 --- a/libs/gfx/source/png.cpp +++ b/libs/gfx/source/png.cpp @@ -9,7 +9,7 @@ namespace psemek::gfx { template - basic_pixmap read_png_impl(io::istream & is, png_byte expected_color_type) + basic_pixmap read_png_impl(io::istream & is, bool monochrome) { png_error_ptr error = [](png_structp, png_const_charp str) { @@ -51,15 +51,21 @@ namespace psemek::gfx auto const color_type = png_get_color_type(png, info); auto const bit_depth = png_get_bit_depth(png, info); - if (color_type != expected_color_type) - throw std::runtime_error("PNG color type not supported"); - if (bit_depth == 16) png_set_strip_16(png); + if (monochrome && color_type != PNG_COLOR_TYPE_GRAY) + throw std::runtime_error("invalid color type for monochrome PNG"); + + if (color_type == PNG_COLOR_TYPE_PALETTE) + png_set_palette_to_rgb(png); + if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand_gray_1_2_4_to_8(png); + if (color_type == PNG_COLOR_TYPE_RGB) + png_set_add_alpha(png, 0xff, PNG_FILLER_AFTER); + png_read_update_info(png, info); basic_pixmap result({width, height}); @@ -76,12 +82,12 @@ namespace psemek::gfx pixmap_rgba read_png(io::istream && is) { - return read_png_impl(is, PNG_COLOR_TYPE_RGBA); + return read_png_impl(is, false); } pixmap_monochrome read_png_monochrome(io::istream && is) { - return read_png_impl(is, PNG_COLOR_TYPE_GRAY); + return read_png_impl(is, true); } }