Search code examples
layerrgbaflatten

Flattening image layers


I am working on a basic image editing tool with support for layers, and I need to know how to merge the layers into a single image. Obviously, if the pixels have no alpha value, then whichever is on top wins, but I dont know what to do when the pixels have alpha values. So here's the question: Given two (or more) pixels represented using RGBA values, how do I merge them into a single pixel in this context (layers)?

TIA


Solution

  • For each component in an layer, if the alpha value is a (range 0..1) then you'll see a proportion a of that component + a proportion 1-a of what's underneath.

    Try working from the bottom layer to the top layer.

    EDIT:

    #define MAX_PIXEL 255
    
    int numLayers; // Number of layers.
    Color* layers; // Pointer to the layers.
    
    Color flattened;
    
    flattened.R = 0;
    flattened.G = 0;
    flattened.B = 0;
    flattened.A = MAX_PIXEL;
    
    // Layer 0 is the bottom layer.
    for (int i = 0; i < numLayers; i++) {
        int alpha;
    
        alpha = layers[i].A;
    
        flattened[i].R = (layers[i].R * alpha + flattened[i].R * (MAX_PIXEL - alpha)) / MAX_PIXEL;
        flattened[i].G = (layers[i].G * alpha + flattened[i].G * (MAX_PIXEL - alpha)) / MAX_PIXEL;
        flattened[i].B = (layers[i].B * alpha + flattened[i].B * (MAX_PIXEL - alpha)) / MAX_PIXEL;
    }