I have VARCHAR in the database for colors. The format is rrr,ggg,bbb (example 225,225,0).
How can I convert that String into java.awt.Color and visualize it in a JSF page?
Do this :
1. Read you color column value
2. Split your string values with , or any other separator you have used
3. Parse each value to Integer value
4. Passed this value into java.awt.color constructors.
Sample Example :
int red,green,blue;
String colorStr = "225,225,0"; //Value from DB
String[] ar_color = colorStr.split(",");
red = Integer.parseInt(ar_color[0]);
green = Integer.parseInt(ar_color[1]);
blue = Integer.parseInt(ar_color[2]);
Color myColor = new Color(red, green, blue);
I would parse the database entry and cast the values to integers, then you can use one of the constructors for a java.awt.color.
However I am not sure that is what you want. You want to use this color value in one of your JSF pages.
You might be setting a color on a component like this :
this.myComponent.setStyle("color:'225,225,0'");
So you could dynamically then change the color like this from the DB :
this.myComponent.setStyle("color:" + myColorStringFromDB);
No need to convert to a java color.
Create a Color object, using the values you have
Color color = new Color(int rrr, int ggg, int bbb)
Example
Color color = new Color(255, 255, 0)
Related
I am writing a program where I take an image determine the average red channel, green channel and blue channel present in that image. I take these averages and pass them as parameters to a new color. I then want to add this color to an array. I repeat this process 24 times. The problem I face is that when I get a new color and add it to the array the previous colors get erased. I want to preserve the existing colors in the array and add to the one that hasn't been filled yet. Here is what I have tried.
System.out.println("R: "+ rAvg);
System.out.println("G: "+ gAvg);
System.out.println("B: "+ bAvg);
Color newColor = new Color(rAvg, gAvg, bAvg);
Color[] ColorArr = new Color[24];
for(int i = 0; i < ColorArr.length; i++){
ColorArr[i] = newColor;
}
System.out.println(Arrays.toString(ColorArr));
Here is the output after one color is added to the array
R: 206
G: 0
B: 0
[java.awt.Color[r=206,g=0,b=0],java.awt.Color[r=206,g=0,b=0]
Here is the array after I add a new color.
R: 211
G: 178
B: 230
[java.awt.Color[r=211,g=178,b=230], java.awt.Color[r=211,g=178,b=230]
The last color gets overwritten and replaced with the new color instead of going in the next index and preserving the last. How can I fix this so I preserve the entered colors in the array and place the new color the index after the previous?
You can restructure your code to something like this:
private Color[] colorArray = new Color[24];
private int currentIndex = 0;
public void addColorToArray(int red, int green, int blue) {
colorArray[currentIndex++] = new Color(red, green, blue);
}
public void myMethodThatDoThis24Times() {
addColorToArray(getRedAverage(), getGreenAverage(), getBlueAverage());
addColorToArray(getRedAverage(), getGreenAverage(), getBlueAverage());
...
}
Your logic looks correct. The only thing which you need to take care is creating a new instance of color object every time.
//ColorArr[i] = newColor; // Instead of this
ColorArr[i] = new Color(rAvg, gAvg, bAvg); // Do this for each element in array
You were initially doing Color newColor = new Color(rAvg, gAvg, bAvg); and assign the same newColor instance to all the elements in the ColorArr.
Thus, a single change in the newColor instance was reflecting the change in all its referenced elements in the array.
As #user alayor, rightly suggested to create new instances of Color(rAvg, gAvg, bAvg) with different RGB values.
The code:
String green = "#99FFCC";
adjustColor(green);
private int adjustColor(String color){
int colorToAdjust = Color.parseColor(color);
//Pseudocode
int red = colorToAdjust.getRed(); //get red value from RGB
red *= 0.5; //halve it
colorToAdjust.setRed(red); //set red value
return colorToAdjust;
}
Given a string hex color, I parse it to an int. How do I change the individual RGB colors? Above is a somewhat pseudo-code of what I'm trying to do: parse hex, get individual color, change it, write it back
You can simply extract the amount of Red by calling red() function and then create the new color based on the original values of Blue & Green and the halved value of the Red you extracted before.
You can then create the new color by calling the rgb() function and passing it the new values of Red, Green & Blue.
Here is the code snippet:
String green = "#99FFCC";
adjustColor(green);
private int adjustColor(String color) {
/* Get RGB Value Of Color */
int colorToAdjust = Color.parseColor(color);
/* Get Red Value From RGB */
int redAmount = Color.red(colorToAdjust);
/* Return New Color By Halving Red */
return Color.rgb(0.5 * redAmount, Color.green(colorToAdjust),
Color.blue(colorToAdjust));
}
You can have a look at this Reference for more information.
I want to extract the R,G and B values of the pixels of an image. I do it in two ways.
File img_file = new File("../foo.png");
BufferedImage img = ImageIO.read(img_file);
1st method(which works fine):
img.getRaster().getPixel(i, j, rgb);
2nd method(which throws new IllegalArgumentException("More than one component per pixel"))
red = img.getColorModel().getRed(img.getRGB(i, j));
What is the reason for this behaviour?
Normally when I want to extract RGB from a BufferedImage I do something like this:
File img_file = new File("../foo.png");
BufferedImage img = ImageIO.read(img_file);
Color color = new Color(img.getRGB(i,j));
int red = color.getRed();
Based on the JavaDocs
An IllegalArgumentException is thrown if pixel values for this
ColorModel are not conveniently representable as a single int
It would suggest that the underlying color model is representable by a single int value
You may also want to take a look at this answer for some more details
Typically, you would simply take the int packed pixel from the image and use Color to generate a Color representation and then extract the values from there...
First, get the int packed value of the pixel at x/y...
int pixel = img.getRGB(i, j);
Use this to construct a Color object...
Color color = new Color(pixel, true); // True if you care about the alpha value...
Extract the R, G, B values...
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
Now you could simply do some bit maths, but this is simpler and is more readable - IMHO
I am trying to modify a third party software. I want to use a color which is returned by some methods (which I cant modifiy) as an integer. However, I would like to use RGB format, like #FF00FF. How can I make a conversion?
Here is an HTML example http://www.shodor.org/stella2java/rgbint.html
I would like to archive same thing in Java, on Android.
What I found to be the simplest and best solution for me was to directly use the Color class as follows:
int red = Color.red(intColor);
int green = Color.green(intColor);
int blue = Color.blue(intColor);
int alpha = Color.alpha(intColor);
This way I could already deal with the integer values without having to handle strings. If on the other hand the string representing the rgb color is what you need, Pankaj Kumar's answer is the best. I hope this is useful to someone.
Use this
String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
We know lenght of color value in HEX is 6. So you see 6 here. %06X matches the result coming from (0xFFFFFF & intColor) and if length is less than 6, it makes result with 6 by appending ZERO to left side of result. And you see #, so this # char gets appended to result and finally you get a HEX COLOR value.
Update since API 26
Since API 26, new methods Color.valueOf(....) has been introduced to convert colors for similar reason. you can use it like
// sRGB
Color opaqueRed = Color.valueOf(0xffff0000); // from a color int
Color translucentRed = Color.valueOf(1.0f, 0.0f, 0.0f, 0.5f);
// Wide gamut color
ColorSpace sRgb = ColorSpace.get(ColorSpace.Named.SRGB);
#ColorLong long p3 = Color.pack(1.0f, 1.0f, 0.0f, 1.0f, sRgb);
Color opaqueYellow = Color.valueOf(p3); // from a color long
// CIE L*a*b* color space
ColorSpace lab = ColorSpace.get(Named.CIE_LAB);
Color green = Color.valueOf(100.0f, -128.0f, 128.0f, 1.0f, lab);
mView.setBackgroundColor(opaqueRed.toArgb());
mView2.setBackgroundColor(green.toArgb());
mView3.setBackgroundColor(translucentRed.toArgb());
mView4.setBackgroundColor(opaqueYellow.toArgb());
Since SDK 26 you can just use
Color c = Color.valueOf(colorInt);
apart from that it does not seem to possible to create a Color instance from arbitrary argb. The underlying code uses a private constructor:
/**
* Creates a new <code>Color</code> instance from an ARGB color int.
* The resulting color is in the {#link ColorSpace.Named#SRGB sRGB}
* color space.
*
* #param color The ARGB color int to create a <code>Color</code> from
* #return A non-null instance of {#link Color}
*/
#NonNull
public static Color valueOf(#ColorInt int color) {
float r = ((color >> 16) & 0xff) / 255.0f;
float g = ((color >> 8) & 0xff) / 255.0f;
float b = ((color ) & 0xff) / 255.0f;
float a = ((color >> 24) & 0xff) / 255.0f;
return new Color(r, g, b, a, ColorSpace.get(ColorSpace.Named.SRGB));
}
RGB uses hexa decimal number format,.
if you have integer value, convert it to hexa,.
It seems the value being quoted and the format desired are mismatched. The value is hexadecimal, while RGB would read 255, 0, 255 and the integer is a composite color representation. Since it is unclear what is being accomplished, here are all three variations:
If you have an integer for the composite color, then most color endpoints will accept it unmodified. This would be something like setBackgroundColor(colorInt)
If you have the hexadecimal value, then Color.parseColor(#colorHex) would convert it to a color object.
Likewise, Color.rgb(redInt, greenInt, blueInt) would convert the red, green, and blue values to a color object.
If you need to restore the composite integer into a color object, that is even simpler with Color.valueOf(colorInt)
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?
String.format("#%06x", color.getRGB() & 0x00FFFFFF)
The masking is used for removing the alpha component, in bits 24-31
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
Read this: Getting Html color codes with a JColorChooser
The answer has a method to convert a color to it's hex value.
There is another way. Thought I just add this alternative.
// ARGB = (255, 255, 0, 0) (Red)
// hex -> "ffff0000"
String hex = Integer.toHexString(color.getRGB());
// Reduced to RGB: hex -> "#ff0000"
hex = "#" + hex.substring(2, hex.length());