Rgb to Hex and Hex to Rgb

RGB to hex and hex to RGB

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

Convert rgb strings to hex in Javascript

I would at first cut away the CSS parts:

var a = "rgb(255,255,255)".split("(")[1].split(")")[0];

Then split it into separate numbers:

a = a.split(",");

Convert the single numbers to hex

var b = a.map(function(x){             //For each array element
x = parseInt(x).toString(16); //Convert to a base16 string
return (x.length==1) ? "0"+x : x; //Add zero if we get only one character
})

And glue it back together:

b = "0x"+b.join("");

Convert Hex to RGBA

//If you write your own code, remember hex color shortcuts (eg., #fff, #000)

function hexToRgbA(hex){
var c;
if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){
c= hex.substring(1).split('');
if(c.length== 3){
c= [c[0], c[0], c[1], c[1], c[2], c[2]];
}
c= '0x'+c.join('');
return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+',1)';
}
throw new Error('Bad Hex');
}

hexToRgbA('#fbafff')

/* returned value: (String)
rgba(251,175,255,1)
*/

Convert RGB Color to HEX color

Solution:

Just use:

String hex = String.format("#%02x%02x%02x", redValue, greenValue, blueValue);

This will convert all the Red, Green and Blue values to Hex String.

Hope it helps.

How to get hex color value rather than RGB value?

var hexDigits = new Array
("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");

//Function to convert rgb color to hex format
function rgb2hex(rgb) {
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function hex(x) {
return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
}

(Source)

RGB to hex and hex to RGB

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


Related Topics



Leave a reply



Submit