假设我想要在 Java 中使用 25% 或 31% 的灰色?
以下代码显示
BufferedImage image = new BufferedImage(2, 2, BufferedImage.TYPE_BYTE_GRAY);
image.setRGB(0, 0, new Color(0,0,0).getRGB());
image.setRGB(1, 0, new Color(50, 50, 50).getRGB());
image.setRGB(0, 1, new Color(100,100,100).getRGB());
image.setRGB(1, 1, new Color(255,255,255).getRGB());
Raster raster = image.getData();
double[] data = raster.getPixels(0, 0, raster.getWidth(), raster.getHeight(), (double[]) null);
System.out.println(Arrays.toString(data));
显而易见的事实是,RGC 与密度 (?) 非线性相关
[0.0, 8.0, 32.0, 255.0]
那么,如何创建给定密度的颜色呢?
更新
我已经尝试过@icza 和@hlg 提出的方法以及我发现的另一种方法:
double[] data;
Raster raster;
BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_GRAY);
float[] grays = {0, 0.25f, 0.5f, 0.75f, 1};
ColorSpace linearRGB = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB);
ColorSpace GRAY = ColorSpace.getInstance(ColorSpace.CS_GRAY);
Color color;
int[] rgb;
for(int i=0; i<grays.length; ++i) {
System.out.println("\n\nShould be " + (grays[i]*100) + "% gray");
color = new Color(linearRGB, new float[] {grays[i], grays[i], grays[i]}, 1f);
image.setRGB(0, 0, color.getRGB());
raster = image.getData();
data = raster.getPixels(0, 0, 1, 1, (double[]) null);
System.out.println("data by CS_LINEAR_RGB (hlg method) = " + Arrays.toString(data));
color = new Color(GRAY, new float[] {grays[i]}, 1f);
image.setRGB(0, 0, color.getRGB());
raster = image.getData();
data = raster.getPixels(0, 0, 1, 1, (double[]) null);
System.out.println("data by CS_GRAY = " + Arrays.toString(data));
rgb = getRGB(Math.round(grays[i]*255));
color = new Color(rgb[0], rgb[1], rgb[2]);
image.setRGB(0, 0, color.getRGB());
raster = image.getData();
data = raster.getPixels(0, 0, 1, 1, (double[]) null);
System.out.println("data by icza method = " + Arrays.toString(data));
}
并且都给出了不同的结果!
Should be 0.0% gray
data by CS_LINEAR_RGB (hlg method) = [0.0]
data by CS_GRAY = [0.0]
data by icza method = [0.0]
Should be 25.0% gray
data by CS_LINEAR_RGB (hlg method) = [63.0]
data by CS_GRAY = [64.0]
data by icza method = [36.0]
Should be 50.0% gray
data by CS_LINEAR_RGB (hlg method) = [127.0]
data by CS_GRAY = [128.0]
data by icza method = [72.0]
Should be 75.0% gray
data by CS_LINEAR_RGB (hlg method) = [190.0]
data by CS_GRAY = [192.0]
data by icza method = [154.0]
Should be 100.0% gray
data by CS_LINEAR_RGB (hlg method) = [254.0]
data by CS_GRAY = [254.0]
data by icza method = [255.0]
现在我想知道哪个是正确的?
更新 2
抱歉,灰/白百分比当然应该颠倒过来。