Pick the color of a pixel in the Image Editor

Hi
I would like the create a script which gives me the rbga value of a pixel that I pick in the Image Editor.
I’m looking to do something like when I clic in the Image Editor with the left mouse, it returns me a list with the rbga value of the pixel I pick and launch a function in the script for exemple. Is it possible to do that?

Thank you!!

there’s a stock color picker you could use for this, but well, if you want to code it yourself:

import bpy

class ModalDrawOperator(bpy.types.Operator):
    """Draw a line with the mouse"""
    bl_idname = "view3d.modal_operator"
    bl_label = "Simple Modal View3D Operator"


    def modal(self, context, event):
        context.area.tag_redraw()


        if event.type == 'LEFTMOUSE':
            mouse_x = event.mouse_x - context.region.x
            mouse_y = event.mouse_y - context.region.y


            uv = context.area.regions[-1].view2d.region_to_view(mouse_x, mouse_y)
            img = context.area.spaces[0].image
            size_x, size_y = img.size[:]


            x = int(size_x * uv[0]) % size_x
            y = int(size_y * uv[1]) % size_y


            offset = (y * size_x + x) * 4
            pixels = img.pixels[offset:offset+4]


            self.report({'INFO'}, "Color: %.3f %.3f %.3f %.3f (RGBA)" % pixels)
            
            # Overwrite pixel (for testing purposes):
            #img.pixels[offset:offset+4] = (1,1,1,1)
            
            return {'FINISHED'}


        elif event.type in {'RIGHTMOUSE', 'ESC'}:
            return {'CANCELLED'}


        return {'RUNNING_MODAL'}


    def invoke(self, context, event):
        if context.area.type == 'IMAGE_EDITOR':
            context.window_manager.modal_handler_add(self)
            return {'RUNNING_MODAL'}
        else:
            self.report({'WARNING'}, "UV/Image Editor not found, cannot run operator")
            return {'CANCELLED'}




def register():
    bpy.utils.register_class(ModalDrawOperator)




def unregister():
    bpy.utils.unregister_class(ModalDrawOperator)


if __name__ == "__main__":
    register()

Use spacebar menu over image editor and search for the modal operator, then left-click on a pixel. You might need to add checks in case there’s no image or something like that.

Thank you for the script! I think that is exactly what I need.

I don’t want to code a color picker from scratch but the color picker of Blender clamps the values greater than 1 and smaller than 0. And that’s a problem for the tools I’m working on.

Well, it clamps to positive values, but not to a maximum of 1:


Indeed, I probably make a mistake when I tried to sample the colors greater than 1. Anyway, I also need to sample values smaller than 0 and your script helps me a lot.
Thanks.