I'm trying to load an image from jpeg file and to add the material to the cube using the following code:

bpy.ops.image.open(filepath="/root/carteid_dini.png", directory="/root/", files=[{"name":"carteid_dini.png", "name":"carteid_dini.png"}], relative_path=True, show_multiview=False)

# get material reference
mat = bpy.context.view_layer.objects.active.active_material

# get texture reference
tex = bpy.data.images.get('carteid')

# create node and assing the texture to it
image_node = mat.node_tree.nodes.new('ShaderNodeTexImage')
image_node.image = tex

mat.node_tree.links.new(image_node.outputs['Color'], mat.node_tree.nodes['Principled BSDF'].inputs['Base Color'], verify_limits=True)

cube = bpy.context.active_object

if len(cube.material_slots) == 0:

cube.material_slots[0].material= mat

When I run this code, the newly created texture is unfortunately not loaded and the image is not selected for the 'Base Color'.

Q: How to load an image from the disc and and assign it to an arbitrary image texture node?

  • $\begingroup$ I don't know how to share this question via email from the web interface $\endgroup$
    – Dini
    Nov 9 '20 at 17:03

You can use BlendDataImages.load() to load and assign the image to the texture node in one go. Following example code is based on Control Cycles material nodes and material properties.

import bpy

# Get the material
mat = bpy.context.object.active_material
# Get the nodes
nodes = mat.node_tree.nodes

# Clear all nodes to start clean

# Create Principled Shader node
node_principled = nodes.new(type='ShaderNodeBsdfPrincipled')
node_principled.location = 0,0

# Create Image Texture node
node_tex = nodes.new('ShaderNodeTexImage')
# Assign the image
node_tex.image = bpy.data.images.load("//your_image.exr")
node_tex.location = -400,0

# Create Output node
node_output = nodes.new(type='ShaderNodeOutputMaterial')   
node_output.location = 400,0

# Link all nodes
links = mat.node_tree.links
link = links.new(node_tex.outputs["Color"], node_principled.inputs["Base Color"])
link = links.new(node_principled.outputs["BSDF"], node_output.inputs["Surface"])

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.