001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.imaging.palette;
018
019import java.util.Collections;
020import java.util.List;
021
022import org.apache.commons.imaging.ImageWriteException;
023
024public class QuantizedPalette implements Palette {
025    private final int precision;
026    private final List<ColorSpaceSubset> subsets;
027    private final ColorSpaceSubset[] straight;
028
029    public QuantizedPalette(final List<ColorSpaceSubset> subsets, final int precision) {
030        this.subsets = subsets == null ? Collections.emptyList() : Collections.unmodifiableList(subsets);
031        this.precision = precision;
032
033        straight = new ColorSpaceSubset[1 << (precision * 3)];
034
035        for (int i = 0; i < this.subsets.size(); i++) {
036            final ColorSpaceSubset subset = subsets.get(i);
037            subset.setIndex(i);
038
039            for (int u = subset.mins[0]; u <= subset.maxs[0]; u++) {
040                for (int j = subset.mins[1]; j <= subset.maxs[1]; j++) {
041                    for (int k = subset.mins[2]; k <= subset.maxs[2]; k++) {
042                        final int index = (u << (precision * 2))
043                                | (j << (precision * 1))
044                                | (k << (precision * 0));
045                        straight[index] = subset;
046                    }
047                }
048            }
049        }
050    }
051
052    @Override
053    public int getPaletteIndex(final int rgb) throws ImageWriteException {
054        final int precisionMask = (1 << precision) - 1;
055
056        final int index = ((rgb >> (24 - 3 * precision)) & (precisionMask << (precision << 1)))
057                | ((rgb >> (16 - 2 * precision)) & (precisionMask << precision))
058                | ((rgb >> (8 - precision)) & (precisionMask));
059
060        return straight[index].getIndex();
061    }
062
063    @Override
064    public int getEntry(final int index) {
065        final ColorSpaceSubset subset = subsets.get(index);
066        return subset.rgb;
067    }
068
069    @Override
070    public int length() {
071        return subsets.size();
072    }
073}