Get RGB color of a specific screen location

hh hh at hyperhh.de
Mon Jan 7 10:02:36 EST 2019


> Beat C. wrote:
> What I need is to get the RGB of a specific screen
> location - I need to make an avarage of e.g. 5x5 pixels.

Make a new small stack with a button. Script it as given below.
On mouseUp the average is taken from the 5x5-rect left of the topleft
of your stack.

----- begin button script
local t="temp"

-- hL,vL is the topleft of the pixel-rect on your screen
-- the width  of the pixel-rect is w. W is an integer >= 1.
-- the height of the pixel-rect is h. H is an integer >= 1.
-- average color is taken from the pixel-colors of rect (hL,vL,hL+w,vL+h)
function averageColor w,h,hL,vL
   export snapshot from rect (hL,vL,hL+w,vL+h) to img t as PNG
   put the rect of img t &" / " &the width of img t,the height of img t into fld "OUT"
   put the imagedata of img t into iData
   put the imagedata of img t into aData
   repeat with i=1 to w*h
      put byteToNum(byte 4*i-2 of iData) into redA[i]
      put byteToNum(byte 4*i-1 of iData) into greenA[i]
      put byteToNum(byte 4*i   of iData) into blueA[i]
      put byteToNum(byte i     of aData) into alphaA[i]
   end repeat
   return trunc(avg(redA)),trunc(avg(greenA)),trunc(avg(blueA)),trunc(avg(alphaA))
end averageColor

on mouseUp
   lock screen; lock messages
   put 5 into w0; put 5 into h0
   put -w0+the left of this stack into sL 
   put -h0+the top of this stack into sT -- = without window bar
   ####
   if there is no img "temp" then create invisible img t
   if there is no field t then
      create fld t
      set rect of fld t to (0,0,128,23)
      set botleft of fld t to the botright of me
   end if
   if there is no grc t then
      create grc t
      set opaque of grc t to true
      set rect of grc t to (0,0,23,23)
      set botright of grc t to the botleft of me
   end if
   ####
   put averageColor(w0,h0,sL,sT) into x --> returns r,g,b,alpha
   #### use x, for example:
   set backColor of grc t to item 1 to 3 of x
   -- set blendlevel of grc t to round(100*(1-(item 4 of x)/255)) -- if wanted
   put x into fld t
   unlock screen; unlock messages
end mouseUp

--- end button script



More information about the use-livecode mailing list