Renaming Textures to Imagefilename

Hi all,

i got a script running that batchimports my wavefront *.obj files, modifies the Material naming Datablocks and sets some BGE settings. Now the last task i have to accomplish is to rename the Textures in Relation to there Images.

I´ve learned much on this bumpy road from 3ds MAX to Blender but somehow this is way over my head.

The imported files have multiple objects with multiple materials and UV maps. Every Material has at least one Texture file associated but max 1.
The Textures should be used in a library afterwards so need to rename them to their original *.png naming but without the “.png” ending ofc.

Herer are my 2 scripts im using right now. Blender is invoked through cmd.

# simple script to batch convert obj to blender.
# run as:
# blender --background --python obj2blender.py -- input_dir output_dir
 
import os
import sys
import glob
import bpy

if len(sys.argv) != 7:
    print("Must provide input and output path")
else:
    for infile in glob.glob(os.path.join(sys.argv[5], '*.obj')):
        bpy.ops.wm.read_homefile()
        bpy.ops.object.select_all(action='SELECT')
        bpy.ops.object.delete()
        bpy.ops.import_scene.obj(filepath=infile, axis_forward='Y', axis_up='Z')
        bpy.context.scene.render.engine = 'BLENDER_GAME'
        bpy.context.scene.game_settings.material_mode = 'GLSL'
        #bpy.ops.wm.addon_enable(module="object_batch_rename_datablocks")
        bpy.ops.object.select_all(action='SELECT')
        bpy.ops.object.make_single_user(type='ALL',material=True,texture=True)
        bpy.ops.object.batch_rename_datablocks(naming_base='Object', rename_custom="New Name", rename_object=False, rename_data=True, rename_material=True, rename_use_prefix=False, rename_prefix="", prefix_object=True, prefix_data=True, prefix_material=True)
        
        
        for item in bpy.data.materials:
                #Change Materials
               item.specular_hardness = 1
               item.game_settings.alpha_blend = 'CLIP'
               item.game_settings.use_backface_culling = False
        outfilename = os.path.splitext(os.path.split(infile)[1])[0] + ".blend"
        bpy.ops.wm.save_as_mainfile(filepath=os.path.join(sys.argv[6], outfilename))

And here the Material renaming script… Thanks for that great script tstscr! :smiley:


# ##### BEGIN GPL LICENSE BLOCK #####
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####

bl_info = {
    "name": "Batch Rename Datablocks",
    "author": "tstscr",
    "version": (1, 0),
    "blender": (2, 59, 0),
    "location": "Search > (rename)",
    "description": "Batch renaming of datablocks (e.g. rename materials after objectnames)",
    "warning": "",
    "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.6/Py/"\
        "Scripts/Object/Batch_Rename_Datablocks",
    "tracker_url": "http://projects.blender.org/tracker/index.php?"\
        "func=detail&aid=25242",
    "category": "Object"}


import bpy
from bpy.props import *

def get_first_material_name(ob):
    for m_slot in ob.material_slots:
        if m_slot.material:
            material_name = m_slot.material.name
            return material_name

def get_name(self, ob):
    if self.naming_base == 'Object':
        return ob.name
    
    if self.naming_base == 'Mesh':
        if ob.data: return ob.data.name
        else: return ob.name
    
    if self.naming_base == 'Material':
        material_name = get_first_material_name(ob)
        if not material_name: return ob.name
        else: return material_name

    if self.naming_base == 'Custom':
        return self.rename_custom
    
    
def rename_datablocks_main(self, context):
    obs = context.selected_editable_objects
    for ob in obs:
        name = get_name(self, ob)
        
        if self.rename_object:
            if (self.rename_use_prefix
            and self.prefix_object):
                ob.name = self.rename_prefix + name
            else:
                ob.name = name
        
        if self.rename_data:
            if (ob.data
            and ob.data.users == 1):
                if (self.rename_use_prefix
                and self.prefix_data):
                    ob.data.name = self.rename_prefix + name
                else:
                    ob.data.name = name
        
        if self.rename_material:
            if ob.material_slots:
                for m_slot in ob.material_slots:
                    if m_slot.material:
                        if m_slot.material.users == 1:
                            if (self.rename_use_prefix
                            and self.prefix_material):
                                m_slot.material.name = self.rename_prefix + name
                            else:
                                m_slot.material.name = name

class OBJECT_OT_batch_rename_datablocks(bpy.types.Operator):
    """Batch rename Datablocks"""
    bl_idname = "object.batch_rename_datablocks"
    bl_label = "Batch Rename Datablocks"
    bl_options = {'REGISTER', 'UNDO'}
    
    name_origins = [
                    ('Object', 'Object', 'Object'),
                    ('Mesh', 'Mesh', 'Mesh'),
                    ('Material', 'Material', 'Material'),
                    ('Custom', 'Custom', 'Custom')
                    ]
    naming_base = EnumProperty(name='Name after:',
                                items=name_origins)
    rename_custom = StringProperty(name='Custom Name',
                                default='New Name',
                                description='Rename all with this String')
    rename_object = BoolProperty(name='Rename Objects',
                                default=False,
                                description='Rename Objects')
    rename_data = BoolProperty(name='Rename Data',
                                default=True,
                                description='Rename Object\'s Data')
    rename_material = BoolProperty(name='Rename Materials',
                                default=True,
                                description='Rename Objects\' Materials')
    rename_use_prefix = BoolProperty(name='Add Prefix',
                                default=False,
                                description='Prefix Objectnames with first Groups name')
    rename_prefix = StringProperty(name='Prefix',
                                default='',
                                description='Prefix name with this string')
    prefix_object = BoolProperty(name='Object',
                                default=True,
                                description='Prefix Object Names')
    prefix_data = BoolProperty(name='Data',
                                default=True,
                                description='Prefix Data Names')
    prefix_material = BoolProperty(name='Material',
                                default=True,
                                description='Prefix Material Names')

    dialog_width = 260

    def draw(self, context):
        layout = self.layout
        col = layout.column()
        col.label(text='Rename after:')
        
        row = layout.row()
        row.prop(self.properties, 'naming_base', expand=True)
        
        col = layout.column()
        col.prop(self.properties, 'rename_custom')

        col.separator()
        col.label('Datablocks to rename:')
        col.prop(self.properties, 'rename_object')
        col.prop(self.properties, 'rename_data')
        col.prop(self.properties, 'rename_material')
        
        col.separator()
        col.prop(self.properties, 'rename_use_prefix')
        col.prop(self.properties, 'rename_prefix')
        
        row = layout.row()
        row.prop(self.properties, 'prefix_object')
        row.prop(self.properties, 'prefix_data')
        row.prop(self.properties, 'prefix_material')
        
        col = layout.column()
        
    @classmethod
    def poll(cls, context):
        return context.selected_objects != None

    def execute(self, context):

        rename_datablocks_main(self, context)
        
        return {'FINISHED'}

    def invoke(self, context, event):
        wm = context.window_manager
        wm.invoke_props_dialog(self, self.dialog_width)
        return {'RUNNING_MODAL'}
        
        
def register():
    bpy.utils.register_module(__name__)
    pass
def unregister():
    bpy.utils.unregister_module(__name__)
    pass
if __name__ == '__main__':
    register()

I could really use some help. :wink: This would be my last step before i can head on with this big project. :rolleyes:

Thanks guys

So, in the Wavefront obj import script of Blender 2.66 (import_obj.py)we got this lines…

    #==================================================================================#
    # This function sets textures defined in .mtl file                                 #
    #==================================================================================#
    def load_material_image(blender_material, context_material_name, imagepath, type):
        

        texture = bpy.data.textures.new(name=type, type='IMAGE')

        # Absolute path - c:\.. etc would work here
        image = obj_image_load(imagepath, DIR, use_image_search)
        has_data = False
        image_depth = 0

        if image is not None:
            texture.image = image
            # note, this causes the image to load, see: [#32637]
            # which makes the following has_data work as expected.
            image_depth = image.depth
            has_data = image.has_data

How would you tell the texture to write the correct bpy.data.images names with [:-4] instead of the name=type???

Any ideas guys? :smiley:

Greets gerrylix, im really confused on this… :spin:

2 Beers and a discussion with my flatmate later, here we go…

Thats how you rename a Textureslot by its Image.

    for x in range(0,len(bpy.data.textures)):
        if bpy.data.textures[x].type == 'IMAGE':
            bpy.data.textures[x].name = bpy.data.textures[x].image.name[:-4]

Cheers guys

for x in range(0,len(bpy.data.textures)):
    if bpy.data.textures[x].type == 'IMAGE':
        bpy.data.textures[x].name = bpy.data.textures[x].image.name[:-4]

Dah! I can’t stand ugly code…

Do:

for tex in bpy.data.textures:
    if tex.type == 'IMAGE':
        name = tex.name.rsplit(".", 1) # Should be save enough
        tex.name = name