Read more

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

Arne Hartherz
March 18, 2021Software engineer at makandra GmbH

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]
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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)"
Posted by Arne Hartherz to makandra dev (2021-03-18 11:17)