2
$\begingroup$

I am writing a custom export script for blender and need to copy the textures from the materials texture slots to another location. I am using shutil for copyfile:

copyfile(bpy.path.abspath(texture.image.filepath), export_path + filename)

This works, as long as the texture isn't linked from another .blend file. In this case, texture.image.filepath returns the path relative to the source blend file, not the current working file. bpy.path.abspath then just appends it to the current working directory, which is wrong of course. How to deal with this?

$\endgroup$

1 Answer 1

2
$\begingroup$

Not very nice, but it's working.

import os
import bpy

tex = bpy.data.images['WALL_1773.png']
# linked image from /project/assets/shaders/walls.blend

tex_path = tex.filepath
# '//../textures/walls/WALL_1773.png'

blend_dir_path = os.path.dirname(tex.library.filepath)
# '/project/assets/shaders'

full_path = blend_dir_path + tex_path[1:]
# '/project/assets/shaders/../textures/walls/WALL_1773.png'

norm_path = os.path.normpath(full_path)
# '/project/assets/textures/walls/WALL_1773.png'

Better code based on batFINGER's comment

import os
import bpy

tex = bpy.data.images['WALL_1773.png']
# linked image from /project/assets/shaders/walls.blend

full_path = bpy.path.abspath(tex.filepath, library=tex.library)
# '/project/assets/shaders/../textures/walls/WALL_1773.png'

norm_path = os.path.normpath(full_path)
# '/project/assets/textures/walls/WALL_1773.png'

$\endgroup$
4
  • $\begingroup$ Certainly nice enough, since blender doesn't provide that out of the box (which i think is kind of a flaw) $\endgroup$
    – theCNG27
    Commented May 7, 2019 at 20:33
  • $\begingroup$ I've edit my answer - there are should be full_path = blend_dir_path + tex_path[1:] instead of full_path = os.path.dirname(blend_dir_path) + tex_path[1:]. Because we use os.path.dirname() in the previous line (blend_dir_path = os.path.dirname(tex.library.filepath)) $\endgroup$ Commented May 8, 2019 at 12:37
  • 1
    $\begingroup$ Also check out bpy.path.abspath(tex.filepath, library=tex.library) Recommend never adding path strings, use os.path.join(...). $\endgroup$
    – batFINGER
    Commented May 8, 2019 at 12:47
  • $\begingroup$ I just forgot about os.path.join() =) Thanks for bpy.path.abspath! Edited one more time. $\endgroup$ Commented May 8, 2019 at 13:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .