Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A way of getting a corresponding hex colour code given a Color object in Java?

I've inspected the Java class documentation for Color and found that I can generate a Color object from a hex code string (e.g. "#FFFFFF") using the Color.decode(); method.

I would like to implement the reverse process for a project I am working on, but there doesn't seem to be a method already built in to the class for this.

Is there an easy way to do this?

like image 325
HellaWiggly Avatar asked Feb 27 '13 13:02

HellaWiggly


People also ask

How do you convert RGB to hexadecimal?

First ValueTake the first number, 220, and divide by 16. 220 / 16 = 13.75, which means that the first digit of the 6-digit hex color code is 13, or D. Take the remainder of the first digit, 0.75, and multiply by 16. 0.75 (16) = 12, which means that the second digit of the 6-digit hex color code is 12, or C.


2 Answers

String.format("#%06x", color.getRGB() & 0x00FFFFFF)

The masking is used for removing the alpha component, in bits 24-31

like image 56
Eyal Schneider Avatar answered Nov 12 '22 14:11

Eyal Schneider


Color color = Color.BLUE;
Formatter f = new Formatter(new StringBuffer("#"));
f.format("%02X", color.getRed());
f.format("%02X", color.getGreen());
f.format("%02X", color.getBlue());
f.toString(); //#0000FF
like image 38
Nikita Tkachenko Avatar answered Nov 12 '22 12:11

Nikita Tkachenko