Skip to content

Instantly share code, notes, and snippets.

@peetzweg
Last active July 26, 2020 17:04
Show Gist options
  • Save peetzweg/049fc12fb49f2e9a469f9624153193ab to your computer and use it in GitHub Desktop.
Save peetzweg/049fc12fb49f2e9a469f9624153193ab to your computer and use it in GitHub Desktop.
Hammerspoon Color Picker Script
local modifier = {"alt"}
function rgbToHex(red, green, blue)
return "#" .. string.format("%x", red) .. string.format("%x", green) ..
string.format("%x", blue)
end
function hslToRgb(h, s, l)
if s == 0 then return l, l, l end
local function to(p, q, t)
if t < 0 then t = t + 1 end
if t > 1 then t = t - 1 end
if t < .16667 then return p + (q - p) * 6 * t end
if t < .5 then return q end
if t < .66667 then return p + (q - p) * (.66667 - t) * 6 end
return p
end
local q = l < .5 and l * (1 + s) or l + s - l * s
local p = 2 * l - q
return to(p, q, h + .33334), to(p, q, h), to(p, q, h - .33334)
end
function round(number)
if (number > 0.5) then
return math.min(255, math.ceil(number * 255.9999))
else
return math.min(255, math.floor(number * 255.9999))
end
end
function pickColor()
local absolute = hs.mouse.getAbsolutePosition()
local rectToShot = hs.geometry.rect(absolute.x, absolute.y, 10, 10)
local screen = hs.mouse.getCurrentScreen()
local snapshot = screen:snapshot(rectToShot)
local color = snapshot:colorAt(hs.geometry.point(0, 0))
-- -- Convert RGB to Hex
local red = round(color.red)
local green = round(color.green)
local blue = round(color.blue)
-- Hex Value is not on Point, maybe use HSB?
local hex = rgbToHex(red, green, blue)
-- Show to user and copy to clipboard
hs.alert.show(hex)
hs.alert.show(red .. "," .. green .. "," .. blue)
hs.pasteboard.writeDataForUTI(nil, "public.utf8-plain-text", hex)
end
local leftClickTap = hs.eventtap.new({hs.eventtap.event.types.leftMouseDown},
pickColor)
hs.hotkey.bind(modifier, "a", function() leftClickTap:start() end,
function() leftClickTap:stop() end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment