4
$\begingroup$

I made a plugin to use on blender, installing the plugin will display a panel, and I wanted to display an image on that panel, so I create a texture in the script file with type 'IMAGE':

 ui_tex = bpy.data.textures.new('MP', 'IMAGE')

and then when I assign it an image it doesn't seem to load the image:

ui_tex.image = bpy.data.images.load("D:/pic.png")

So how can I load an image from the script file to a newly created texture. Note: the previous two python statements are written in a draw function of the panel

Edit: Here is the class for the panel with the draw function:

class UIPanel(bpy.types.Panel):

  bl_label = "Label"
  bl_space_type = "VIEW_3D"
  bl_region_type = "TOOLS"
  br_name = "Printing"

  def draw(self, context):

   layout = self.layout
   scn = context.scene

   ui_tex = bpy.data.textures.new("MP", "IMAGE")
   ui_tex.image = bpy.data.images.load("D:/pic.png")

   row = layout.row(align=True)
   row.alignment = 'EXPAND'
   row.template_preview(bpy.data.textures["MP"])

Might I add that I get this error in the blender system console:

line 39, in draw
ui_tex.image = bpy.data.images.load(filepath = filepath)
AttributeError: Writing to ID classes in this context is not allowed: MP, Texture datablock, error setting ImageTexture.image
$\endgroup$
4
  • $\begingroup$ I suggest adding a larger section of your code to the question so we can see how you are going about things currently. $\endgroup$ Commented Feb 8, 2017 at 10:14
  • $\begingroup$ Okay I did, please find the extra code $\endgroup$ Commented Feb 8, 2017 at 11:02
  • $\begingroup$ You cannot alter ID object's properties in a draw method. It's for drawing data to the UI, and runs a lot (a lot) of times per second. This is by design. Which for your example above is a good idea otherwise you would be loading and loading and loading the same image over and over. This would be a handy addition to the Gotchas $\endgroup$ Commented Feb 8, 2017 at 15:30
  • $\begingroup$ Related blender.stackexchange.com/questions/43710/… $\endgroup$ Commented Feb 8, 2017 at 18:34

1 Answer 1

2
$\begingroup$

Blender v2.79

Load image to texture:

bpy.ops.image.open(filepath='full_path_to/your_image.png')
bpy.data.images['your_image.png'].pack(as_png=True) # Pack an image as embedded data into the .blend file
ui_tex.image = bpy.data.images['your_image.png']

Don't forget to replace 'full_path_to/your_image.png' to your own values.

EDIT:

I think this method is easier, you simply load the node, given its name and then set the path:

im_node = scene.node_tree.nodes["Image"]
im_node.image.filepath = 'full_path_to/your_image.png'
$\endgroup$
1
  • $\begingroup$ In Blender v2.8 use instead bpy.data.images['your_image.png'].pack() $\endgroup$ Commented Jan 8, 2020 at 21:01

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.