1
$\begingroup$

I am trying to add the content of a image to the surface of a mesh on Blender 2.80, but the better I have achieved was to apply the image color to surface. I am using cycles renderer.

I have this function so far, it takes the path to the image and the mesh object as arguments.

def add_texture(texture_path, obj):
    mat = bpy.data.materials.new(name='texture')
    mat.use_nodes = True
    nodes = mat.node_tree.nodes

    texImage = nodes.new('ShaderNodeTexImage')
    texImage.image = bpy.data.images.load(texture_path)

    # What to link here?
    # mat.node_tree.links.new()

    # Assign it to object
    if obj.data.materials:
        obj.data.materials[0] = mat
    else:
        obj.data.materials.append(mat)

I created a material added the image as a texture, It seems that I have to link some attribute of the texture to the material, but I cannot find what I have to do exactly.

Any ideas on how to apply the image content to the mesh surface?

$\endgroup$
2
  • $\begingroup$ mat.use_nodes = True => Principled and Output are created. Get the principled node and add link (links.new) using texImage.Outputs[0] and principled.Inputs[0] (base color). $\endgroup$
    – lemon
    Commented Sep 25, 2019 at 18:31
  • $\begingroup$ How do I get a reference to the Principled? Would this be the link mat.node_tree.links.new(texImage.Outputs[0], principled.Inputs[0]['Base Color']) $\endgroup$
    – czr
    Commented Sep 25, 2019 at 18:36

1 Answer 1

1
$\begingroup$

You can complete your code with the following, considering mat.use_nodes = True creates automatically a principled BSDF node.

import bpy

def add_texture(texture_path, obj):
    mat = bpy.data.materials.new(name='texture')
    mat.use_nodes = True
    nodes = mat.node_tree.nodes

    texImage = nodes.new('ShaderNodeTexImage')
    texImage.image = bpy.data.images.load(texture_path)

    principled = nodes['Principled BSDF']

    # What to link here?
    # mat.node_tree.links.new()
    mat.node_tree.links.new( texImage.outputs[0], principled.inputs[0] )

    # Assign it to object
    if obj.data.materials:
        obj.data.materials[0] = mat
    else:
        obj.data.materials.append(mat)

obj = bpy.context.object

add_texture( "your path to texture file", obj )
$\endgroup$
2
  • $\begingroup$ Thank you. By doing that only what seems to be the average color of the image is applied to the mesh surface. What could be causing that, could it be related to the scale of the images? $\endgroup$
    – czr
    Commented Sep 25, 2019 at 18:52
  • $\begingroup$ Should not be the case... this is nodes as usual. A uv map issue? $\endgroup$
    – lemon
    Commented Sep 25, 2019 at 18:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .