Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RGB to hex and hex to RGB

How to convert colors in RGB format to hex format and vice versa?

For example, convert '#0080C0' to (0, 128, 192).

like image 501
Sindar Avatar asked Apr 11 '11 15:04

Sindar


People also ask

Is HEX and RGB same?

There is no informational difference between RGB and HEX colors; they are simply different ways of communicating the same thing – a red, green, and blue color value. HEX, along with its sister RGB, is one of the color languages used in coding, such as CSS. HEX is a numeric character based reference of RGB numbers.

Is it better to use RGB or HEX?

When it comes to animating colors, working in RGB or HSL is preferable over HEX simply because numbers are easier to edit dynamically.


1 Answers

Note: both versions of rgbToHex expect integer values for r, g and b, so you'll need to do your own rounding if you have non-integer values.

The following will do to the RGB to hex conversion and add any required zero padding:

function componentToHex(c) {   var hex = c.toString(16);   return hex.length == 1 ? "0" + hex : hex; }  function rgbToHex(r, g, b) {   return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b); }  alert(rgbToHex(0, 51, 255)); // #0033ff

Converting the other way:

function hexToRgb(hex) {   var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);   return result ? {     r: parseInt(result[1], 16),     g: parseInt(result[2], 16),     b: parseInt(result[3], 16)   } : null; }  alert(hexToRgb("#0033ff").g); // "51";

Finally, an alternative version of rgbToHex(), as discussed in @casablanca's answer and suggested in the comments by @cwolves:

function rgbToHex(r, g, b) {   return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); }  alert(rgbToHex(0, 51, 255)); // #0033ff

Update 3 December 2012

Here's a version of hexToRgb() that also parses a shorthand hex triplet such as "#03F":

function hexToRgb(hex) {   // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")   var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;   hex = hex.replace(shorthandRegex, function(m, r, g, b) {     return r + r + g + g + b + b;   });    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);   return result ? {     r: parseInt(result[1], 16),     g: parseInt(result[2], 16),     b: parseInt(result[3], 16)   } : null; }  alert(hexToRgb("#0033ff").g); // "51"; alert(hexToRgb("#03f").g); // "51";
like image 192
Tim Down Avatar answered Sep 18 '22 12:09

Tim Down