Skip to content

Instantly share code, notes, and snippets.

@neroist
Last active March 13, 2024 06:55
Show Gist options
  • Save neroist/63b4ff02e4c0a51a8fd4ce0fa856761d to your computer and use it in GitHub Desktop.
Save neroist/63b4ff02e4c0a51a8fd4ce0fa856761d to your computer and use it in GitHub Desktop.
Converts color temperature in kelvin to RGB. Nim Port of https://tannerhelland.com/2012/09/18/convert-temperature-rgb-algorithm-code.html
## Port by: Jasmine / "neroist" on Github
## Orginial pseudocode algorithm:
##
## Start with a temperature, in Kelvin, somewhere between 1000 and 40000. (Other values may work,
## but I can't make any promises about the quality of the algorithm's estimates above 40000 K.)
## Note also that the temperature and color variables need to be declared as floating-point.
##
## Set Temperature = Temperature \ 100
##
## Calculate Red:
##
## If Temperature <= 66 Then
## Red = 255
## Else
## Red = Temperature - 60
## Red = 329.698727446 * (Red ^ -0.1332047592)
## If Red < 0 Then Red = 0
## If Red > 255 Then Red = 255
## End If
##
## Calculate Green:
##
## If Temperature <= 66 Then
## Green = Temperature
## Green = 99.4708025861 * Ln(Green) - 161.1195681661
## If Green < 0 Then Green = 0
## If Green > 255 Then Green = 255
## Else
## Green = Temperature - 60
## Green = 288.1221695283 * (Green ^ -0.0755148492)
## If Green < 0 Then Green = 0
## If Green > 255 Then Green = 255
## End If
##
## Calculate Blue:
##
## If Temperature >= 66 Then
## Blue = 255
## Else
##
## If Temperature <= 19 Then
## Blue = 0
## Else
## Blue = Temperature - 10
## Blue = 138.5177312231 * Ln(Blue) - 305.0447927307
## If Blue < 0 Then Blue = 0
## If Blue > 255 Then Blue = 255
## End If
##
## End If
from std/math import pow, ln
func kelvinToRgb*(temp: int): tuple[r, g, b: int] =
## Converts color temperature to rgb
## Algorithim from https://tannerhelland.com/2012/09/18/convert-temperature-rgb-algorithm-code.html
let temp = temp.clamp(1000, 40000) / 100
# calculate both red and green
# since the if stmts they're in have the same condition
if temp <= 66:
result.r = 255
result.g = int (99.4708025861 * ln(temp) - 161.1195681661).clamp(0.0, 255.0) # We cast it into int so it can be used practically
else:
result.r = int (329.698727446 * (pow(temp - 60, -0.1332047592))).clamp(0.0, 255.0)
result.g = int (288.1221695283 * (pow(temp - 60, -0.0755148492))).clamp(0.0, 255.0)
# calculate blue
if temp >= 66:
result.b = 255
elif temp <= 19:
result.b = 0
else:
result.b = int (138.5177312231 * ln(temp - 10) - 305.0447927307).clamp(0.0, 255.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment