1 /*
2  * Copyright (C) 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.internal.graphics.palette;
18 
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26 
27 /**
28  * Converts a set of pixels/colors into a map with keys of unique colors, and values of the count
29  * of the unique color in the original set of pixels.
30  *
31  * This allows other quantizers to get a significant speed boost by simply running this quantizer,
32  * and then performing operations using the map, rather than for each pixel.
33  */
34 public final class QuantizerMap implements Quantizer {
35     private HashMap<Integer, Integer> mColorToCount;
36     private Palette mPalette;
37 
38     @Override
quantize(@onNull int[] pixels, int colorCount)39     public void quantize(@NonNull int[] pixels, int colorCount) {
40         final HashMap<Integer, Integer> colorToCount = new HashMap<>();
41         for (int pixel : pixels) {
42             colorToCount.merge(pixel, 1, Integer::sum);
43         }
44         mColorToCount = colorToCount;
45 
46         List<Palette.Swatch> swatches = new ArrayList<>();
47         for (Map.Entry<Integer, Integer> entry : colorToCount.entrySet()) {
48             swatches.add(new Palette.Swatch(entry.getKey(), entry.getValue()));
49         }
50         mPalette = Palette.from(swatches);
51     }
52 
53     @Override
getQuantizedColors()54     public List<Palette.Swatch> getQuantizedColors() {
55         return mPalette.getSwatches();
56     }
57 
58     @Nullable
getColorToCount()59     public Map<Integer, Integer> getColorToCount() {
60         return mColorToCount;
61     }
62 }
63