Skip to content

Instantly share code, notes, and snippets.

@R0bl0x10501050
Created August 4, 2021 01:08
Show Gist options
  • Save R0bl0x10501050/977147fc7ce593a45733d58748de847c to your computer and use it in GitHub Desktop.
Save R0bl0x10501050/977147fc7ce593a45733d58748de847c to your computer and use it in GitHub Desktop.
Invert a hex or RGB table (in R,G,B order).
-- Based on:
-- https://stackoverflow.com/questions/35969656/
local base16 = {
['0'] = 'F',
['1'] = 'E',
['2'] = 'D',
['3'] = 'C',
['4'] = 'B',
['5'] = 'A',
['6'] = '9',
['7'] = '8',
['8'] = '7',
['9'] = '6',
['A'] = '5',
['B'] = '4',
['C'] = '3',
['D'] = '2',
['E'] = '1',
['F'] = '0',
}
local split = function(inputstr, sep)
local t = {}
if sep == nil then
return {inputStr}
elseif sep == "" then
for str in string.gmatch(inputstr, "([^.])") do
table.insert(t, str)
end
else
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
table.insert(t, str)
end
end
return t
end
local round = function(x)
-- https://stackoverflow.com/questions/18313171
return x>=0 and math.floor(x+0.5) or math.ceil(x-0.5)
end
local invert = function(color, bw)
-- Check if RGB or HEX
if type(color) == 'string' then
-- Remove # symbol
local hex = color:gsub("#", "")
-- Convert 3 to 6
if (hex:len() == 3) then
local one, two, three = split(hex, "")[1], split(hex, "")[2], split(hex, "")[3]
hex = one .. one .. two .. two .. three .. three
end
-- Error if invalid
if (hex:len() ~= 6) then
error('Invalid HEX color!')
end
-- Reverse HEX
local splitStr = split(hex, "")
local newHex = ''
local newRGB = ''
table.foreachi(splitStr, function(_,v)
newHex = newHex .. base16[string.upper(tostring(v))]
end)
-- Get RGB components from HEX
local r = tonumber(split(newHex, "")[1]..split(newHex, "")[2], 16)
local g = tonumber(split(newHex, "")[3]..split(newHex, "")[4], 16)
local b = tonumber(split(newHex, "")[5]..split(newHex, "")[6], 16)
-- Check black/white color
if (bw) then
if (r * 0.299 + g * 0.587 + b * 0.114) > 186 then
return {255,255,255}
else
return {0,0,0}
end
end
return {r, g, b}
elseif type(color) == 'table' then
-- Get RGB components
local r, g, b = color[1], color[2], color[3]
-- Invert RGB components
local invertedRed, invertedGreen, invertedBlue = round(255 - r), round(255 - g), round(255 - b)
-- Check black/white color
if (bw) then
if (r * 0.299 + g * 0.587 + b * 0.114) > 186 then
return {255,255,255}
else
return {0,0,0}
end
end
return {invertedRed, invertedGreen, invertedBlue}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment