1
$\begingroup$

I'm trying to create a picture in Blender using only Python/scripting (no animation). I have a model loaded in and I can change it's base color using active_material.diffuse_color but now I want to put a texture on the model and then change the texture color. I've googled for a while and couldn't find any good resources for how to do so.

This is what I have so far:

mat = bpy.data.materials.new(name="Material")
mat.use_nodes = True
bsdf = mat.node_tree.nodes["Principled BSDF"]
texImage = mat.node_tree.nodes.new('ShaderNodeTexImage')
texImage.image = bpy.data.images.load("../textures/texture.png")
mat.node_tree.links.new(bsdf.inputs['Base Color'], texImage.outputs['Color'])

color_ramp = mat.node_tree.nodes.new("ShaderNodeValToRGB")
mat.node_tree.links.new(bsdf.inputs['Base Color'], color_ramp.outputs['Color'])

ob = bpy.data.objects['model']
if ob.data.materials:
    ob.data.materials[0] = mat
else:
    ob.data.materials.append(mat)

The code correctly puts the texture on the model, but I'm not sure how to use the color_ramp node to actually change the color or if it's even the right thing to try. Thanks!

$\endgroup$
1
1
$\begingroup$

Thanks brockmann, I figured it out from your links.

mat = bpy.data.materials.new(name="Material")
mat.use_nodes = True
bsdf = mat.node_tree.nodes["Principled BSDF"]
color_ramp = mat.node_tree.nodes.new("ShaderNodeValToRGB")
color_ramp.color_ramp.elements[0].color = (0.2,0.8,0.7,1)
mat.node_tree.links.new(bsdf.inputs['Base Color'], color_ramp.outputs['Color'])
texImage = mat.node_tree.nodes.new('ShaderNodeTexImage')
texImage.image = bpy.data.images.load("../textures/Fabric.png")
mat.node_tree.links.new(color_ramp.inputs[0], texImage.outputs['Color'])

ob = bpy.data.objects['model']
if ob.data.materials:
    ob.data.materials[0] = mat
else:
    ob.data.materials.append(mat)
```
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.