JXA - Get Pixel color of picture file

Over the past few days I have been working on this function. Today I had a brainwave and managed to complete the function. Here it is! Hope you find a use for it!

function getPixelColor(picturePath,x,y){
   ObjC.import('Foundation')
   ObjC.import('AppKit')
   
   //Get image from file
   var img = $.NSImage.alloc.initWithContentsOfFile($(picturePath))
   
   //If img is objC's nil then return a blank array
   if(img==$()){
    return []
   }
   
   //Get a point object
   var pnt = $.NSMakePoint(x,y)
   
   //Target the image
   img.lockFocus
   
   //Target read point from target
   var clr = $.NSReadPixel(pnt)
   
   //Untarget the image
   img.unlockFocus
   
   //Release img - saving memory
   img.release
   
   //Return R,G,B and A
   return [
           parseInt(255*clr.redComponent),    
           parseInt(255*clr.greenComponent),
           parseInt(255*clr.blueComponent),
           clr.alphaComponent
        ];
}

Usage example:

getPixel("/Users/Sancarn/Pictures/RedSquare.png",10,10)

I personally hope that with this I can finally read the time from screenflow!

From my calculations it should be a minimum of 32 pixel checks per time read. That’s assuming I can find a perfect set of pixels for the checks… Which might be pretty tricky… But hey, there’s no fun without a challenge right!?

2 Likes

This is really neat. Thank you for sharing.