算法链接:
overlay - Overlaying pixels with alpha value in C/C++ - Stack Overflow
核心实现
#define OPAQUE 0xFF;
#define TRANSPARENT 0;
#define ALPHA(rgb) (uint8_t)(rgb >> 24)
#define RED(rgb) (uint8_t)(rgb >> 16)
#define GREEN(rgb) (uint8_t)(rgb >> 8)
#define BLUE(rgb) (uint8_t)(rgb)
#define UNMULTIPLY(color, alpha) ((0xFF * color) / alpha)
#define BLEND(back, front, alpha) ((front * alpha) + (back * (255 - alpha))) / 255
#define ARGB(a, r, g, b) (a << 24) | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF)
void ImageUtil::overlay(const uint32_t* front, uint32_t* back, const unsigned int width, const unsigned int height)
{
const size_t totalPixels = width * height;
for (unsigned long index = 0; index < totalPixels; index++)
{
const uint32_t frontAlpha = ALPHA(*front);
if (frontAlpha == TRANSPARENT)
{
*back++;
*front++;
continue;
}
if (frontAlpha == OPAQUE)
{
*back++ = *front++;
continue;
}
const uint8_t backR = RED(*back);
const uint8_t backG = GREEN(*back);
const uint8_t backB = BLUE(*back);
const uint8_t frontR = UNMULTIPLY(RED(*front), frontAlpha);
const uint8_t frontG = UNMULTIPLY(GREEN(*front), frontAlpha);
const uint8_t frontB = UNMULTIPLY(BLUE(*front), frontAlpha);
const uint32_t R = BLEND(backR, frontR, frontAlpha);
const uint32_t G = BLEND(backG, frontG, frontAlpha);
const uint32_t B = BLEND(backB, frontB, frontAlpha);
*back++ = ARGB(OPAQUE, R , G, B);
*front++;
}
}