1
$\begingroup$

I am trying to assign an image texture to an Image Texture node in 2.80. Very simple script - I'm just starting to learn how this stuff works.

This is what I have. It creates an image and and IT node, but it doesn't assign the one to other. Can anybody help? I've searched around, but can't find it in another question.

import bpy

#create blank image
bpy.ops.image.new(name="TestImg", width=1024, height=1024)

#add image texture to object, to hold baked lighting
mat = bpy.context.view_layer.objects.active.active_material
image_node = mat.node_tree.nodes.new('ShaderNodeTexImage')

#assign image to image texture node
image_node.image = "TestImg"

Thanks in advance.

$\endgroup$
1
$\begingroup$

The texture is not assigned because you are referring to it as a String instead of a data. Use the following code:

import bpy

# create blank image
bpy.ops.image.new(name="TestImg", width=1024, height=1024)

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

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

# create node and assing the texture to it
image_node = mat.node_tree.nodes.new('ShaderNodeTexImage')
image_node.image = tex
$\endgroup$
  • $\begingroup$ .. or image_node.image = bpy.data.images.new("TestImg", 1024, 1024) $\endgroup$ – batFINGER Apr 15 at 10:08
  • $\begingroup$ It works! Thanks for the help both of you. I like the more efficient method from batFINGER, though think I'll keep the longer version in my code as it helps me with keeping the process super clear whilst I'm still learning. Extra thanks to bat, as it was your limited dissolve loop (blender.stackexchange.com/questions/69081/…) that inspired me to start writing my own scripts in the first place. $\endgroup$ – edna Apr 16 at 1:56
  • $\begingroup$ @edna cheers... that old answer received an edit. Made meshes a set in case objects were sharing a mesh. $\endgroup$ – batFINGER Apr 16 at 12:46

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.