Save 'Render Result' as a specific path/name

Hello there!
I have been trying to create some automation scripts for my current game project. While I have been monkeying with the bge module for quite some time, I am still very new to the bpy API.
I have been scouring the internet for the right solution to my issue, but for whatever reason, I’m just not finding it.

My issue is simple. I have a script that is to take multiple renders of different angles of an object. The script takes a snapshot, rotates the object, and repeats a number of times.

What I’m stuck on, is how to actually get python to ‘Save As’ the render result, give it an appropriate name, and place it in a relative path to the blend file (if my blend is in /game, the images should be piped out to /game/sprite/).

This is the method that renders/saves an image:

def render(direction):
	PATH = path.relpath('/sprite/')
	scene = context.scene
	scene.render.image_settings.file_format = 'PNG'
	image = data.images['Render Result']

This code is obviously broken, but hopefully it illustrates what I’m trying to accomplish.
The end result, I should see a sprite folder alongside my blend, with a series of images called say idle_0.png, idle_1.png, idle_2.png, etc.

I think my big problem is not understanding how to put ops.image.save_as() into proper ‘context’. At least, this is the error I get when running this script:
“RuntimeError: Operator bpy.ops.image.save_as.poll() failed, context is incorrect”

I don’t understand how ops.image.save_as() is figuring which image is ‘the image’ it’s using. I want to make sure it’s using what I’ve defined as ‘image’.

Am I just approaching this the wrong way? What can I do to make this do what I want it to?

The save_as() operator requires the UV / Image editor as context. But instead of doing either of:

… you can just avoid that operator and use an equivalent RNA method instead:

import bpyimport os
from math import radians
from mathutils import Matrix

ob = bpy.context.object
mat = Matrix.Rotation(radians(45), 4, 'Z')

blend_path =
assert blend_path # abort if .blend is not unsaved
blend_path = os.path.dirname(bpy.path.abspath(blend_path))

dirpath = os.path.join(blend_path, "sprite")

filepath = os.path.join(dirpath, "frame{}.png")
scene = bpy.context.scene
scene.render.image_settings.file_format = 'PNG'

for i, step in enumerate(range(0, 360, 45)):
    ob.matrix_world *= mat
    bpy.ops.render.render()["Render Result"].save_render(filepath.format(i))