Extracting Colors In Android 5.0 – “The Palette API”

Before the new update of Palette’s API in android 5.0 developers were allowed to extract colors from images.

Now with the release of Android Lollipop, the Palette class makes easy to extract prominent colors from bitmap images. These colors are very useful if you want to style other view components to match colors from your image, such as a background for the image or a text color etc.

We have two different ways to create the Palette for an image. First is to use the generate methods, which either take just a bitmap object or a bitmap with an integer specifying the number of colors the palette should generate.

 

 

 

These methods are synchronous and should not be called on the main thread.

But practically, sometimes it may not be possible to do this on the same thread where you load your images on. To solve this the Palette class has another set of generating methods which are asynchronous. The only difference between the two is a listener object that will be called when the Palette is ready.

 

 

 

The implementation of the theory I just explained is very simple. Let’s follow the steps to create a sample code:

Step1:) Create a new android project in your IDE and add following dependency in you gradle build file:

 

 

 

Step2:) Write the following in main layout file:

 

 

 

Step3:) Add a png file to your drawble folder.

Step4:) Write the following into your main activity file:

 

 

 

Step5:) Run for the output.

extracrtcolors1

It is showing only one color extracted from the image which I have set to text view because I haven’t specified any number when I called palette.generates() method. You can create a list or array of swatches to extract more colors.

Leave a Comment: