Get the RGB value from a PNG

foundation
asobjc

(Jonas Whale) #1

In a PNG file (or a TIFF) filled with a unique flat color, I need to get the RGB value of any pixel, let say at position {10,10} from the upper left corner.

Is it possible with AppleScriptObjC?


(Shane Stanley) #2

Sure:

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set imagePath to POSIX path of (choose file)
set imageRep to current application's NSBitmapImageRep's imageRepWithContentsOfFile:imagePath
set theColor to imageRep's colorAtX:10 y:10
set theRed to theColor's redComponent()
set theGreen to theColor's greenComponent()
set theBlue to theColor's blueComponent()
set theAlpha to theColor's alphaComponent()

(Jonas Whale) #3

Perfect!

I made a little update for my needs.
The image is a rectangle exported from Indesign meant to go in Powerpoint.
To get the accurate values, I need to convert the color space.
Don’t ask me why!

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set imagePath to POSIX path of (choose file)
set tempRep to current application's NSBitmapImageRep's imageRepWithContentsOfFile:imagePath
set imageRep to tempRep's bitmapImageRepByConvertingToColorSpace:(current application's NSColorSpace's genericRGBColorSpace()) renderingIntent:0
set theColor to imageRep's colorAtX:50 y:50
set theRed to round ((theColor's redComponent()) * 256) rounding down
set theGreen to round ((theColor's greenComponent()) * 256) rounding down
set theBlue to round ((theColor's blueComponent()) * 256) rounding down
set theAlpha to theColor's alphaComponent()
set theSpace to theColor's colorSpace()
{theRed, theGreen, theBlue, theAlpha, theSpace}