Ruby: How to convert hex color codes to rgb or rgba

Posted . Visible to the public.

When you have a hex color code, you can easily convert it into its RGB values using plain Ruby.

>> "#ff8000".match(/^#(..)(..)(..)$/).captures.map(&:hex)
=> [255, 128, 0]

You can use that to implement a simple "hex to CSS rgba value with given opacity" method:

def hex_color_to_rgba(hex, opacity)
  rgb = hex.match(/^#(..)(..)(..)$/).captures.map(&:hex)
  "rgba(#{rgb.join(", ")}, #{opacity})"
end
>> hex_color_to_rgba("#ff8000", 0.5)
=> "rgba(255, 128, 0, 0.5)"

If you need to support RGBA hex color codes, you need to handle a 4th hex pair. Example:

def hex_color_to_rgba(hex)
  *rgb, alpha = hex.match(/^#(..)(..)(..)(..)?$/).captures.map { |hex_pair| hex_pair&.hex }
  opacity = (alpha || 255) / 255.0
  "rgba(#{rgb.join(", ")}, #{opacity.round(2)})"
end
>> hex_color_to_rgba("#ff8000")
=> "rgba(255, 128, 0, 1)"
>> hex_color_to_rgba("#ff8000aa")
=> "rgba(255, 128, 0, 0.67)"

If you also need to support 3-character hex color codes, it becomes ugly. Note that there is no short RGBA style like #f80a.

def hex_color_to_rgba(hex)
  if hex =~ /^#...$/
    hex = hex.split(//).map { |single| single * 2 }.join[1..]
  end
  *rgb, alpha = hex.match(/^#(..)(..)(..)(..)?$/).captures.map { |hex_pair| hex_pair&.hex }
  opacity = (alpha || 255) / 255.0
  "rgba(#{rgb.join(", ")}, #{opacity.round(2)})"
end
>> hex_color_to_rgba("#f80")
=> "rgba(255, 136, 0, 1)"
>> hex_color_to_rgba("#ff8800")
=> "rgba(255, 136, 0, 1)"
>> hex_color_to_rgba("#ff8800aa")
=> "rgba(255, 136, 0, 0.67)"
Arne Hartherz
Last edit
Emanuel
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2021-03-18 10:17)