Skip to content

Instantly share code, notes, and snippets.

@bearprada
Created March 2, 2016 07:44
Show Gist options
  • Select an option

  • Save bearprada/34aec98ab6f6d5c99bc0 to your computer and use it in GitHub Desktop.

Select an option

Save bearprada/34aec98ab6f6d5c99bc0 to your computer and use it in GitHub Desktop.

Revisions

  1. bearprada created this gist Mar 2, 2016.
    48 changes: 48 additions & 0 deletions AutoSelectBackground.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    /**
    * Background database for lookups of fittest color to represent.
    */
    private static List<Pair<Integer, String>> sBackgrounds = new ArrayList<>();
    static {
    // Color Tickets: ------------A-R-G-B-
    sBackgrounds.add(new Pair<>(0xFF040404, "background_01.png"));
    sBackgrounds.add(new Pair<>(0xFF040404, "background_02.png"));
    sBackgrounds.add(new Pair<>(0xFFF2F2F2, "background_03.png"));
    ...
    sBackgrounds.add(new Pair<>(0xFF362810, "background_99.png"));
    }

    /**
    * Return the fittest background by figuring out the nearest color distance
    * to backgrounds in the database.
    * @param to ARGB color.
    */
    public static String getFittestBackgroundPath(int to) {
    int[] rgb = {Color.red(to), Color.green(to), Color.blue(to)};
    float[] lab1 = ColorSpaces.rgbTolab(rgb);
    String result = sBackgrounds.get(0).second;
    float minDist = Float.MAX_VALUE;

    for (Pair<Integer, String> candidate : sBackgrounds) {
    int ticket = candidate.first;
    int[] rgb2 = {Color.red(ticket),
    Color.green(ticket),
    Color.blue(ticket)};

    float[] lab2 = ColorSpaces.rgbTolab(rgb2);
    // CIE76 ref : https://en.wikipedia.org/wiki/Color_difference#CIE76
    float dist = Math.abs(lab1[0] - lab2[0]) + Math.abs(lab1[1] - lab2[1]) + Math.abs(lab1[2] - lab2[2]);

    if (dist < minDist) {
    minDist = dist;
    result = candidate.second;
    }
    }
    return result;
    }

    public static void main() {
    Bitmap bm = getCollageThumbnail();
    // TODO we shouldn't put the color computation on the main thread.
    int color = Palette.from(bm).generate().getLightVibrantColor(Color.WHITE);
    String backgroundFile = BackgroundBundleManager.getFittestBackgroundPath(color);
    }