Skip to content

Commit b4667ac

Browse files
authored
Handle premultiplied alpha for grayscale PNGs. (#2047)
1 parent 47942dd commit b4667ac

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

core/platform/Image.cpp

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1284,7 +1284,7 @@ bool Image::initWithPngData(uint8_t* data, ssize_t dataLen)
12841284
png_read_end(png_ptr, nullptr);
12851285

12861286
// premultiplied alpha for RGBA8888
1287-
if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
1287+
if ((color_type == PNG_COLOR_TYPE_RGB_ALPHA) || (color_type == PNG_COLOR_TYPE_GRAY_ALPHA))
12881288
{
12891289
if (PNG_PREMULTIPLIED_ALPHA_ENABLED)
12901290
{
@@ -2587,13 +2587,26 @@ bool Image::saveImageToJPG(std::string_view filePath)
25872587
void Image::premultiplyAlpha()
25882588
{
25892589
#if AX_ENABLE_PREMULTIPLIED_ALPHA
2590-
AXASSERT(_pixelFormat == backend::PixelFormat::RGBA8, "The pixel format should be RGBA8888!");
2590+
AXASSERT((_pixelFormat == backend::PixelFormat::RGBA8)
2591+
|| (_pixelFormat == backend::PixelFormat::RG8),
2592+
"The pixel format should be RGBA8888 or RG88.");
25912593

2592-
unsigned int* fourBytes = (unsigned int*)_data;
2593-
for (int i = 0; i < _width * _height; i++)
2594+
if (_pixelFormat == backend::PixelFormat::RGBA8) {
2595+
unsigned int* fourBytes = (unsigned int*)_data;
2596+
for (int i = 0; i < _width * _height; i++)
2597+
{
2598+
uint8_t* p = _data + i * 4;
2599+
fourBytes[i] = AX_RGB_PREMULTIPLY_ALPHA(p[0], p[1], p[2], p[3]);
2600+
}
2601+
}
2602+
else
25942603
{
2595-
uint8_t* p = _data + i * 4;
2596-
fourBytes[i] = AX_RGB_PREMULTIPLY_ALPHA(p[0], p[1], p[2], p[3]);
2604+
uint16_t* twoBytes = (uint16_t*)_data;
2605+
for (int i = 0; i < _width * _height; i++)
2606+
{
2607+
uint8_t* p = _data + i * 2;
2608+
twoBytes[i] = ((p[0] * p[1] + 1) >> 8) | (p[1] << 8);
2609+
}
25972610
}
25982611

25992612
_hasPremultipliedAlpha = true;

0 commit comments

Comments
 (0)