在不使用 java.awt.Color 的情况下从 HSV(Java 中的 HSB)转换为 RGB(在 Google App Engine 上不允许) [英] Converting from HSV (HSB in Java) to RGB without using java.awt.Color (disallowed on Google App Engine)
问题描述
我想我应该发布这个问题,即使我已经找到了解决方案,因为当我搜索它时,Java 实现并不容易获得.
I figured I should post this question, even if I have already found a solution, as a Java implementation was not readily available when I searched for it.
使用 HSV 而不是 RGB 可以生成具有相同饱和度和亮度的颜色(我想要的).
Using HSV instead of RGB allows the generation of colors with the same saturation and brightness (something I wanted).
Google App Engine 不允许使用 java.awt.Color,因此无法执行以下操作来在 HSV 和 RGB 之间进行转换:
Google App Engine does not allow use of java.awt.Color, so doing the following to convert between HSV and RGB is not an option:
Color c = Color.getHSBColor(hue, saturation, value);
String rgb = Integer.toHexString(c.getRGB());
我按照尼克约翰逊的评论中的描述移动了我的答案.
I moved my answer as described in the comment by Nick Johnson.
Ex animo,-亚历山大.
Ex animo, - Alexander.
推荐答案
我对颜色数学一窍不通,但我可以为代码提供这种替代结构,这让我的审美很不舒服,因为它对我来说很明显6 种情况中的每一种情况如何只是值、t 和 p 的不同排列.(此外,我对长的 if-else 链有一种非理性的恐惧.)
I don't know anything about color math, but I can offer this alternative structure for the code, which tickles my aesthetic sense because it made it obvious to me how each of the 6 cases is just a different permutation of value, t and p. (Also I have an irrational fear of long if-else chains.)
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;
}
这篇关于在不使用 java.awt.Color 的情况下从 HSV(Java 中的 HSB)转换为 RGB(在 Google App Engine 上不允许)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!