javascriptnode.jsimage-processingjimp

How do I change the color of a pixel properly?


I'm using jimp to manipulate an image. I'm trying to make something like a selection rectangle that when drawn has a transparent color (#BBBBBBBB). How do I calculate the RGB values I need to set for the pixels? I want to keep the old color and put the transparent color over it and sort of combine them. How can I do that?


Solution

  • "I want to keep the old color and put the transparent color over it and sort of combine them.
    How can I do that?"

    You need interpolation on each color channel (R, G and B).

    In blending color A with color B, you also need to select a point in the A-to-B path (ranging from 0 to 1). Interpolation gives you the color at that point. For example 0.5 is halfway so that point gives a 50/50 blend of two colors. Try it with colors Red and Blue (result is Purple color)

    "How do I calculate the RGB values I need to set for the pixels?"

    var stepPoint = 0.5; //0.5 = 50% blend
    var new_Red   = old_R + stepPoint * (transparent_R - old_R);
    var new_Green = old_G + stepPoint * (transparent_G - old_G);
    var new_Blue  = old_B + stepPoint * (transparent_B - old_B);
    
    //# usage (after interpolation calculations)
    some_Image_Data [i+0] = new_Red;
    some_Image_Data [i+1] = new_Green;
    some_Image_Data [i+2] = new_Blue;
    
    //# or if you want to package as 32-bit integer of RGBA format
    //var mixedColor = ( new_Red << 24) | ( new_Green << 16) | ( new_Blue << 8) | (255);
    

    A faster/easier way might be to just adjust the alpha value of each pixel in the "transparent" image data. This way, when the pixel is set onto another imageData, it already has transparency.

    var idx = 0; //# starting index position in bytes
    while (true)
    {
        if( idx >= some_Image_Data.length ) { break; }
        
        some_Image_Data[idx+3] = 128; //# set between 0-255... lower is more transparent
        idx += 4; //# move on to next pixel
    }