Script to the color and transparency of a pixel in a picture (r,g,b,a)

Hi all, last night I was porting an ObjC script I found on here to JXA-ObjC. I’ve finished the implementation now. Thanks to @tylergaw on twitter for the help!


function getPixel(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:


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


I thought it would also be useful to be able to get the pixel color at a given screen coordinate. To do that you can use this:


function pixelColorAtScreenCoord(displayID,x,y){
	ObjC.import('Foundation')
	ObjC.import('AppKit')
	image = $.CGDisplayCreateImageForRect(displayID,$.CGRectMake(x,y,1,1));
	bitmap = $.NSBitmapImageRep.alloc.initWithCGImage(image)
	$.CGImageRelease(image)
	color = bitmap.colorAtXY($(x),$(y))
    bitmap.release
    return [
			parseInt(255*color.redComponent),	
			parseInt(255*color.greenComponent),
			parseInt(255*color.blueComponent),
			color.alphaComponent
		   ];

	

}

Usage:


pixelColorAtScreenCoord($.CGMainDisplayID(),10,10)

It’s a bit different because you have to get the displayID which proves to be fairly difficult in JXA. This is an easy way to get the screen coord of the main display.