Bpy - Connect existing Image Texture to Material output

Blender artists, I am trying to connect an existing image texture in shader editor to the material output.

Most of the codes I saw online, they created a new material & image texture then connected them to material output.

But I already have my material and texture created, I just need to connect it to material output with python.

I’ll really appreciate the help.

import os, bpy

# new material
mat = bpy.data.materials.new('mat')
matnodes = mat.node_tree.nodes

#new texture
tex = matnodes.new('ShaderNodeTexImage')


# assign texture to material's Surface
Matout = matnodes['Material Output'].inputs[0]
mat.node_tree.links.new(Matout, tex.outputs[0]) 

You’re already almost there- just copy this line and change the parameters for a different node:
Matout = matnodes['Material Output'].inputs[0]
For example,


image = matnodes['Image Texture'].outputs[0]

Here is my scene. I am actually trying to bake lighting/texture for my object

I needed to add image texture to all existing materials on my object then bake (the code in the image). I then removed unused nodes (hence only one material remaining in the scene)

Alt that is left is to connect the image texture to the output.

I answered at BlenderDevTalk.

To preserve against link-rot, I’m copying your answer here:

links = mat.node_tree.links
link = links.new(texture_node.outputs[0], mat.node_tree.nodes.get("Material Output").inputs[0])
1 Like