I am trying to implement gradient map of Photoshop programmatically. Consider below shown gradient map where all white components are replaced by green and black by blue. For other color components Photoshop calculates based on the linear gradient between blue and green. I know there is a math behind this calculation. Does any one know formula to find output color for particular input color value?
For most calculations Photoshop uses every single RGB channel on its own, without regard to the other two (as long as you are in RGB mode, in CMYK mode things might get weird).
Photoshop simply does a linear interpolation for each channel. If we define our colors like that (and assume a 2d gradient starting at 0 to make things easier):
Starting color: [r0, g0, b0] End color: [r1, g1, b1] starting positon: 0 end positon: l current position: p
Now for each point along the line the formula for each channel ist just the following:
r = r0 + ( r1 - r0 ) * (p/(l-1)) )
Lets say you want a gradient from yellow (255, 255, 20) to cyan (0, 255, 200) over a distance of 5 pixels, you end up with that:
0 1 2 3 4 r: 255 192 127 64 0 g: 255 255 255 255 255 b: 20 65 110 155 200
As you can see the change for each channel over the same amount of pixels is always the same (r1 – r0). In this case:
r: -63.75 g: 0 b: +45