开发者

How to add Hue to a given color programmatically?

开发者 https://www.devze.com 2023-02-18 18:29 出处:网络
I tried to implement a my color editor in Java. It should be a simple software. The user will input color in hexadecimal RGBs, for example: 0xFF00FF. I know how to calculate Hue, Chroma, Saturation an

I tried to implement a my color editor in Java. It should be a simple software. The user will input color in hexadecimal RGBs, for example: 0xFF00FF. I know how to calculate Hue, Chroma, Saturation and Lightness, but how to add or substract Hue value to this given color? This is the mystery.

Is there any algorithm or formula to use?

Now I use this method, but I think the result is different from what I got with Adobe Photoshop.

public void addHue(float addHue) {
    float c = getChroma();
    addHue %= 6;
    if (addHue < 2) {
        float n = 1 - green;
        green = green + addHue * n;
    } else if (addHue < 4) {
        addHue -= 2;
        float n = 1 - blue;
        blue = blue + addHue * n;
    } else if (addHue < 6) {
        addHue -=4;
        float 开发者_运维问答n = 1 - red;
        red = red + addHue * n;
    }
    if (green > 1) green = 1;
    else if (green < 0) green = 0;
    if (red > 1) red = 1;
    else if (red < 0) red = 0;
    if (blue > 1) blue = 1;
    else if (blue < 0) blue = 0;
}


The java.awt.Color class can help with this.


I don't really understand what you try to achieve by adding two hues together.

Hue is an angle giving the "tint" of the color you are representing. If you think in degrees, the hue will be in the [0, 360[ range. Also, values of 45 and 405 will be representing the same hue.

You have to take this into account when you want to manipulate hues. That is, is you want to average two values, for instance 355 and 5, the correct result could be 0 (draw a circle and take the smallest half angle between those two values) or 180 (the largest half angle).


How I did it on Android (which does not have the Color manipulation utilities) is to create my own color class that stores both representations of a color (rgb and hsv).

Then I have methods that allow to set RGB or set HSV. Adding in the same color space is trivial. Then each time these methods are called, I respectively call an updateHSV or updateRGB method that computes the color components from the new values.

class Color {
  float[] hsv;
  float[] rgb;

  public void setRgb(float[] rgb) {
    System.arraycopy(rgb, 0, this.rgb, 0, 3);
    computeHsvFromRgb();
  }

  public void setHsv(float[] hsv) {
    System.arraycopy(hsv, 0, this.hsv, 0, 3);
    computeRgbFromHsv();
  }

  // ...
}

For color convertion sample code:

  • http://www.koders.com/java/fid698452C6AA108615D4A611B52D27A9F5819B39F5.aspx?s=stopwatch
  • http://www.f4.fhtw-berlin.de/~barthel/ImageJ/ColorInspector//HTMLHelp/farbraumJava.htm
0

精彩评论

暂无评论...
验证码 换一张
取 消