3

I'm trying to change the texture of an object by changing the .png texture image I'm loading from an external folder.

When using the Blender interface, all I need to do is going to the image tab in texture and open the file I want:

enter image description here

then

enter image description here

The changes are then operated automatically.

How would I go about to do the same in Python?

I have read other stackexchange answers to similar questions but I'm not sure to what extent they apply to my situation.

nayriz
  • 133
  • 1
  • 6

2 Answers2

6

Let's say I have a plane with an image texture called leaf1.png and I want to change the texture to leaf2.png.

If I hover my mouse over the source area, I can see some text at the bottom of the tooltip that says how to access that data with python. Like this:

enter image description here

From this, I know that I can access this with python using bpy.data.images['leaf1.png'].filepath

So to change the image source with python, I do:

import bpy

bpy.data.images['leaf1.png'].filepath = 'path/to/leaf2.png'
doakey3
  • 1,946
  • 11
  • 24
  • 1
    Thank you very much. Your answer clearly does what I was trying to do, but there is one point that somewhat troubles me, namely that that bpy.data.images['leaf1.png'].filepath is now equal to '...leaf2.png'. Is there a way that I could have the command that handles the texture become bpy.data.images['leaf2.png'].filepath ? – nayriz Feb 16 '18 at 07:26
  • 1
    "leaf1.png" is the image name. You can change that too. Just hover your mouse over the leaf1.png and you'll see bpy.data.images['leaf1.png'].name is the python. So you could set the name to "leaf2.png", then use that name to change the filepath. But what's in a name? – doakey3 Feb 16 '18 at 08:06
  • You can enable/disable those 'python tooltips' in the preferences – commonpike Feb 28 '23 at 20:44
0

In Blender 3.1, one can do this:

import bpy

Step 1 - Add Box

bpy.ops.mesh.primitive_cube_add(size=2, location=(0, 0, 0), scale=(1, 1, 1)) box_obj = bpy.context.selected_objects[0] box_obj.name = 'MyBox'

Step 2 - Material

box_material_obj = bpy.data.materials.new(box_obj.name + '-Material') box_material_obj.use_nodes = True

bsdf = box_material_obj.node_tree.nodes["Principled BSDF"] texImage = box_material_obj.node_tree.nodes.new('ShaderNodeTexImage') texImage.image = bpy.data.images.load('myimage.png') box_material_obj.node_tree.links.new(bsdf.inputs['Base Color'], texImage.outputs['Color']) box_obj.data.materials.append(box_material_obj)

Inspired from this blog by paperspace.com

prerakmody
  • 31
  • 2