What's the best way to “round” a Color object to the nearest Color Constant?

后端 未结 3 1863
-上瘾入骨i
-上瘾入骨i 2021-02-04 09:37

I will be retrieving the exact color of a pixel and would like to relate that exact color to a constant like Color.blue. Is there an easy way to \"round\" to the n

3条回答
  •  离开以前
    2021-02-04 10:05

    You can use Java's built-in color conversion with an IndexColorModel containing the palette of possible colors. Internally, the class uses Euclidean distance over the color components to determine the closest color.

    import java.awt.Color;
    import java.awt.image.DataBuffer;
    import java.awt.image.IndexColorModel;
    
    public class ColorConverter {
        private final Color[] colors;
        private final IndexColorModel colorModel;
    
        public ColorConverter(Color[] colors) {
            this.colors = colors;
            this.colorModel = createColorModel(colors);
        }
    
        private static IndexColorModel createColorModel(Color[] colors) {
            final int[] cmap = new int[colors.length];
            for (int i = 0; i

提交回复
热议问题