5

Currently looking at the blender API I haven't seen anything of all about the Hex input. This is frustrating me enough as it seems strange to me that there is no such input function (when Blender natively has it, where it is enough to simply copy and paste).

Now, the point of the situation is that all the scripts I tried, incorrectly convert Hex to RGB (Including some answers those present in other questions about blender.stackexchange).

Basically the conversion from Hex to RGB produces a Hex value different from the Input value, and this is not good, I need absolute precision on these Hex values

I see that it is gamma corrected, now, I don't know much about Hex, so I don't want to comment too much, but I just wish that what I get is the same thing I get by copying an Hex in the RGB node

The most beautiful thing would be to be able to directly input the Hex input value in the RGB node, that gives me exactly the result I want.

Noob Cat
  • 1,222
  • 3
  • 20
  • 61

1 Answers1

12

Hex values are interpreted in the sRGB color space, while Blender uses a linear RGB color space internally. The conversion functions can be found on the sRGB Wikipedia page. The hex channel values themselves (0-255) should be divided by 255 before application of the formulas. A pure Python implementation looks like this:

def srgb_to_linearrgb(c):
    if   c < 0:       return 0
    elif c < 0.04045: return c/12.92
    else:             return ((c+0.055)/1.055)**2.4

def hex_to_rgb(h,alpha=1):
    r = (h & 0xff0000) >> 16
    g = (h & 0x00ff00) >> 8
    b = (h & 0x0000ff)
    return tuple([srgb_to_linearrgb(c/0xff) for c in (r,g,b)] + [alpha])

and using it like so:

bpy.data.materials["Material"].node_tree.nodes["RGB"].outputs[0].default_value = \
    hex_to_rgb(0x123456)

seems to work correctly.

K. A. Buhr
  • 1,978
  • 6
  • 9
  • 1
    Thanks a lot this is precisely what I wanted to get, this is the only answer at the moment on blender.stackexchange which returns correct values, like copying pastes in the RGB node under the heading Hex – Noob Cat Nov 23 '19 at 04:20