# Blender 2.8 (python) - How to set material color using hex value instead of RGB

I would like to rewrite the following script so that I can set the color of the material using a hex value; currently it works with RGB.

A search of the literature provides no suggestions as to how to proceed.

Any advice would be much appreciated!

def add_material(obj, material_name, r, g, b):
material = bpy.data.materials.get(material_name)
if material is None:
material = bpy.data.materials.new(material_name)
material.use_nodes = True
principled_bsdf = material.node_tree.nodes['Principled BSDF']
if principled_bsdf is not None:
principled_bsdf.inputs[0].default_value = (r, g, b, 1)
obj.active_material = material

• Sep 18 '19 at 16:08

You can convert a hex value to rgb like below, using shift and bitwise and operator, then divide it by 255 to get a value between 0 and 1.

import bpy

def hex_to_rgb( hex_value ):
b = (hex_value & 0xFF) / 255.0
g = ((hex_value >> 8) & 0xFF) / 255.0
r = ((hex_value >> 16) & 0xFF) / 255.0
return r, g, b

material = bpy.data.materials.get(material_name)
if material is None:
material = bpy.data.materials.new(material_name)
material.use_nodes = True
principled_bsdf = material.node_tree.nodes['Principled BSDF']
if principled_bsdf is not None:
principled_bsdf.inputs[0].default_value = (*hex_to_rgb(h), 1)
obj.active_material = material

h = 0xE7E7FF

obj = bpy.context.object



Note: you won't obtain the same value in the UI as the hex value is shown gamma corrected.

• Hi Lemon I hope you will excuse me for this disappointment, but this Hex value does not coincide with the Hex value returned by the node color input, in fact if we check the Hex result of this conversion is F4F4FF while your input is E7E7FF Nov 23 '19 at 2:24
• @Pastrokkio, yes as said in the note at the end of the answer the value is gamma corrected in the node field. Nov 24 '19 at 7:29
• Hi , I would like to point out that I received the correct answer to this link, so it can be useful for the comunity blender.stackexchange.com/questions/158896/… Nov 24 '19 at 18:05