Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Hex to RGB?

Tags:

I am trying to use this to figure out if a color is light or dark

Evaluate whether a HEX value is dark or light

Now. It takes in a int

 float calcLuminance(int rgb)  {       int r = (rgb & 0xff0000) >> 16;       int g = (rgb & 0xff00) >> 8;       int b = (rgb & 0xff);        return (r*0.299f + g*0.587f + b*0.114f) / 256;  } 

I have a hex color though.

I tried to do this

  var color = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");   int rgb = color.R + color.G + color.B;    var a = calcLuminance(rgb); 

I got 0.11725 I thought it would have to be in the range of 0-256 or something like that.

What am I doing wrong? Do I have to covert R to an int? Or am I just way off?

like image 579
chobo2 Avatar asked Apr 20 '11 19:04

chobo2


People also ask

Are hex codes for RGB?

A HEX color is expressed as a six-digit combination of numbers and letters defined by its mix of red, green and blue (RGB). Basically, a HEX color code is shorthand for its RGB values with a little conversion gymnastics in between.

What is #ffffff in RGB?

#ffffff color RGB value is (255,255,255). This hex color code is also a web safe color which is equal to #FFF. #ffffff color name is White color. #ffffff hex color red value is 255, green value is 255 and the blue value of its RGB is 255.


2 Answers

Just convert the hex string to an integer:

int color = Convert.ToInt32("FFFFFF", 16); 
like image 165
Chris Haas Avatar answered Sep 22 '22 06:09

Chris Haas


You can use:

public string GenerateRgba(string backgroundColor, decimal backgroundOpacity) {  Color color = ColorTranslator.FromHtml(hexBackgroundColor);  int r = Convert.ToInt16(color.R);  int g = Convert.ToInt16(color.G);  int b = Convert.ToInt16(color.B);  return string.Format("rgba({0}, {1}, {2}, {3});", r, g, b, backgroundOpacity); } 

Link To original Post by jeremy clifton on git

like image 26
Milind Anantwar Avatar answered Sep 20 '22 06:09

Milind Anantwar