如何正确更改像素的颜色?

How do I change the color of a pixel properly?

我正在使用 jimp 来处理图像。我正在尝试制作类似选择矩形的东西,当绘制时具有透明颜色(#BBBBBBBB)。如何计算需要为像素设置的 RGB 值?我想保留旧颜色并将透明颜色放在上面,然后将它们组合起来。我该怎么做?

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

您需要在每个颜色通道(R、G 和 B)上进行 插值

在混合颜色 A 和颜色 B 时,您还需要 select A-to-B 路径中的一个点(范围从 0 到 1)。插值为您提供该点的颜色。例如 0.5 是中间点,因此该点给出两种颜色的 50/50 混合。试试红色和蓝色(结果是紫色)

"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);

一种faster/easier方法可能是调整“透明”图像数据中每个像素的alpha值.这样,当像素设置到另一个图像数据上时,它已经具有透明度。

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
}