Support more PNG color types

This commit is contained in:
Nikita Lisitsa 2023-02-05 00:33:53 +03:00
parent ed1764ffea
commit 417c6f0080

View file

@ -9,7 +9,7 @@ namespace psemek::gfx
{
template <typename Pixel>
basic_pixmap<Pixel> read_png_impl(io::istream & is, png_byte expected_color_type)
basic_pixmap<Pixel> 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<Pixel> result({width, height});
@ -76,12 +82,12 @@ namespace psemek::gfx
pixmap_rgba read_png(io::istream && is)
{
return read_png_impl<color_rgba>(is, PNG_COLOR_TYPE_RGBA);
return read_png_impl<color_rgba>(is, false);
}
pixmap_monochrome read_png_monochrome(io::istream && is)
{
return read_png_impl<std::uint8_t>(is, PNG_COLOR_TYPE_GRAY);
return read_png_impl<std::uint8_t>(is, true);
}
}