Ruby: Converting html colors (24bit) to xterm/terminal colors

Convert nice html color codes into terminal colors
e.g. to make ruco colorful 😀

    COLOR_SOURCE_VALUES = 256
    COLOR_TARGET_VALUES = 5
    COLOR_DIVIDE = COLOR_SOURCE_VALUES / COLOR_TARGET_VALUES
    TERM_COLOR_BASE = 16

    # '#ff0000' => 196
    def self.html_to_terminal_color(html_color)
      return unless html_color
      r = (html_color[1..2].to_i(16) / COLOR_DIVIDE) * 36
      g = (html_color[3..4].to_i(16) / COLOR_DIVIDE) * 6
      b = (html_color[5..6].to_i(16) / COLOR_DIVIDE) * 1
      TERM_COLOR_BASE + r + g + b
    end
Advertisements

2 thoughts on “Ruby: Converting html colors (24bit) to xterm/terminal colors

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s