user8356857
user8356857

Reputation:

Convert RGB Color to HEX color

I am taking a color from an ImageView using OnTouchListener.

Red, Green, Blue color code can be successfully obtained, but i cant convert RGB to HEX ..

example : my rgb values are
r:21

b:16

g:228

and curresponding hex color is #15e410.

i want get #15e410. from r:21 ,b:16 ,g:228

                int pixel = bitmap.getPixel(x,y);             
                int redValue = Color.red(pixel);
                int blueValue = Color.blue(pixel);
                int greenValue = Color.green(pixel);

                int hexa=  Color.rgb(redValue, greenValue, blueValue);


                Toast.makeText(getApplicationContext(),"hexa ::"+hexa ,Toast.LENGTH_LONG).show();

Upvotes: 0

Views: 2025

Answers (4)

LucaRC
LucaRC

Reputation: 1

My Solution:

Function RGBToHex(red As Integer, green As Integer, blue As Integer) As String
    Return String.Format("#{0:X2}{1:X2}{2:X2}", red, green, blue)
End Function

This function takes three integers as input (representing the red, green, and blue values of the color) and returns a string in the format "#RRGGBB" where RR, GG, and BB are the hexadecimal values of the red, green, and blue components of the color.

You can call this function by passing the red, green, and blue values of a color as arguments, like this:

Dim hexColor As String = RGBToHex(255, 0, 0)

Upvotes: 0

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.

Upvotes: 4

Nabin Bhandari
Nabin Bhandari

Reputation: 16379

Use Integer.toHexString(color); to convert an integer to hex string.

Example:

int color = 0xff334433;
String hex = Integer.toHexString(color);
System.out.println(hex); // this prints - ff334433

Upvotes: 0

Alex Bean
Alex Bean

Reputation: 553

You are sending wrong the parameters to the function String.format to get the hexColor.

Try this one:

String hexColor = String.format("#%06X", redValued, greenValue, blueValue);

Upvotes: -1

Related Questions