# How to execute python code after each stroke painted in image editor?

Is there any possibility for that? Modal operator seems to be not suitable for that

You can achieve this by using a scene update handler that monitors the state of the active image in the image editor.

For this technique to work you need to:

1. Create or open an image in the image editor window on the active screen.
2. Save your image to an external file once.
3. Also: the script will save any change to file immediately. If you don't care about that, this solution can work for you.

The example below illustrates how you can set a new random paintbrush color after every stroke.

import bpy, random

def run_if_img_changed( scene ):
im = None
# References the active image in the image editor
for a in bpy.context.screen.areas:
if a.type == 'IMAGE_EDITOR':
for s in a.spaces:
if s.type == 'IMAGE_EDITOR':
im = s.image
break

if im and im.is_dirty:
## Replace the bit in this if clause with your code
print( "Image changed!" )

# Set paintbrush to random color
bpy.data.brushes['TexDraw'].color =  [ random.random() for c in 'rgb' ]

## End of replaceable sample code

# Save image so it will no longer be dirty
im.save() # This line will crash the script if you haven't saved the image to a file yet

bpy.app.handlers.scene_update_post.append( run_if_img_changed )

• Getting image by name is cumbersome. (im = bpy.data.images['Untitled.001']) Is there a way to obtain currently editing image? Nov 3 '16 at 16:04
• @wilddev, You can reference any image there, this is simply the example I used above. This is the name of your image, which you can set in the image editor. Nov 3 '16 at 16:07
• handler function receives just a scene, but not a context of image editor. I don't know how to receive such a context inside a handler function =( Nov 3 '16 at 16:13
• @wilddev, updated to read image from image editor. Lemme know if works as expected. Nov 3 '16 at 16:27