Skip to content

Instantly share code, notes, and snippets.

@sham1
Created May 8, 2023 20:54
Show Gist options
  • Save sham1/3d5c138e683ca1d09c2bbd6ac60d1c48 to your computer and use it in GitHub Desktop.
Save sham1/3d5c138e683ca1d09c2bbd6ac60d1c48 to your computer and use it in GitHub Desktop.
Alpha blending (over) with pre-multiplied ARGB pixels
/*
* Copyright (c) 2023 Jani Juhani Sinervo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdint.h>
void
premul_argb_blend(uint8_t out[static restrict 4],
const uint8_t a[const restrict 4],
const uint8_t b[const restrict 4])
{
uint8_t blue_a = a[0];
uint8_t green_a = a[1];
uint8_t red_a = a[2];
uint8_t alpha_a = a[3];
uint8_t blue_b = b[0];
uint8_t green_b = b[1];
uint8_t red_b = b[2];
uint8_t alpha_b = b[3];
uint8_t blue_out = (255 * blue_a + 255 * blue_b - (blue_b * alpha_a))/255;
uint8_t green_out = (255 * green_a + 255 * green_b - (green_b * alpha_a))/255;
uint8_t red_out = (255 * red_a + 255 * red_b - (red_b * alpha_a))/255;
uint8_t alpha_out = (255 * alpha_a + 255 * alpha_b - (alpha_b * alpha_a))/255;
out[0] = blue_out;
out[1] = green_out;
out[2] = red_out;
out[3] = alpha_out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment