Bake full render of selected objects, then save each baked image under object's name

I have a scene, full of tiled models. Some of the models are duplicate linked. So when i bake the whole scene objects, those that are duplicate linked object, will have their baked images overwritten. So only the last duplicate linked object gets it’s baked image correct.

What i want to do is to loop through selected objects in the scene, bake the shadow map, and save it as {object.name}.jpg

I can loop through the selected objects, i can call bpy.ops.object.bake_image(), but i don’t know how to save the baked image. Calling bpy.ops.image.save_as() throws context errors.

You can use this to save an image:


imgname = "colormap.tga"
try:
    img = bpy.data.images[imgname]
except:
    img = bpy.data.images.new(imgname, 1024, 1024, False, False)
img.save()


Thank you so much.

I came up doing:

img2 = img.copy()
img2.name = “the name of the object.jpg”
img2.save

But i can’t find any images saved as “the name of the object.jpg”. Please teach me how to save the img2 externally

Thank you again

You are right i forgot that part:
use img.filepath to indicate where do u want the image to be saved.
eg: img.filepath = “//”+imgname


ext=".tga"
imgname = mat.name+ext
                
try:
  img = bpy.data.images[imgname]
except:
  img = bpy.data.images.new(imgname, 1024, 1024, False, False)
  img.filepath = "//_Textures\\"+imgname
  img.save()

Solved, final code:

import bpy
objs = bpy.context.selected_objects


for obj in objs:
    obj.select = False

for obj in objs:
    print("baking: "+obj.name)
    img = bpy.data.images[obj.data.name+".jpg"]
    img.file_format = "jpg"
    img.filepath_raw = "//"+obj.name+".jpg"
    obj.select=True
    bpy.ops.object.bake_image()
    obj.select=False
    img.save()

filepath_raw changes the filepath without destroying the image data it seemed.

Thank you so much Mackraken.