在不使用 java.awt.Color 的情况下从 HSV(Java 中的 HSB)转换为 RGB(Google App Engine 不允许)

新手上路,请多包涵

我想我应该发布这个问题,即使我已经找到了解决方案,因为当我搜索它时 Java 实现并不容易获得。

使用 HSV 而不是 RGB 可以生成具有相同饱和度和亮度的颜色(这是我想要的)。

Google App Engine 不允许使用 java.awt.Color,因此不能执行以下操作在 HSV 和 RGB 之间进行转换:

 Color c = Color.getHSBColor(hue, saturation, value);
String rgb = Integer.toHexString(c.getRGB());

编辑:我按照 Nick Johnson 的评论中的描述移动了我的答案。

Ex animo, - 亚历山大。

原文由 yngling 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 505
2 个回答

我对颜色数学一无所知,但我可以为代码提供这种替代结构,这让我觉得很有趣,因为它让我很清楚这 6 种情况中的每一种都是值 t 和 p 的不同排列. (此外,我对长 if-else 链有一种非理性的恐惧。)

 public static String hsvToRgb(float hue, float saturation, float value) {

    int h = (int)(hue * 6);
    float f = hue * 6 - h;
    float p = value * (1 - saturation);
    float q = value * (1 - f * saturation);
    float t = value * (1 - (1 - f) * saturation);

    switch (h) {
      case 0: return rgbToString(value, t, p);
      case 1: return rgbToString(q, value, p);
      case 2: return rgbToString(p, value, t);
      case 3: return rgbToString(p, q, value);
      case 4: return rgbToString(t, p, value);
      case 5: return rgbToString(value, p, q);
      default: throw new RuntimeException("Something went wrong when converting from HSV to RGB. Input was " + hue + ", " + saturation + ", " + value);
    }
}

public static String rgbToString(float r, float g, float b) {
    String rs = Integer.toHexString((int)(r * 256));
    String gs = Integer.toHexString((int)(g * 256));
    String bs = Integer.toHexString((int)(b * 256));
    return rs + gs + bs;
}

原文由 Peter Recore 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用提供的 ColorUtils

 HSLToColor(float\[\] hsl)

[RGBToHSL(int r, int g, int b, float\[\] hsl)]

很容易相互转换的方法!

例如:

 float[] hsl = new float[]{1.5, 2.0, 1.5};
int color = ColorUtils.HSLToColor(hsl);

现在得到颜色

float[] hslStub = new float[3];
float[] hslFromColor = ColorUtils.colorToHSL(color, hslStub);

现在得到hsl

这是 源代码

原文由 cafecat 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题