How to posterize an image by reducing colors in Java

Today’s post will cover an incredibly simplified method for implementing posterization effects in an app. Forget about writing this one out from scratch. That would take forever. Instead we will be harnessing a pre-built API to do all of the hard work for us. It should take about 5 minutes. Not bad, right?

To begin, let’s set up our library. We can do this using Jitpack by adding the following references to pom.xml

Repository reference


Dependency reference


Now let’s invoke filterPosterize and specify our desired number of unique colors to retain.

// Import classes://import com.cloudmersive.client.invoker.ApiClient;//import com.cloudmersive.client.invoker.ApiException;//import com.cloudmersive.client.invoker.Configuration;//import com.cloudmersive.client.invoker.auth.*;//import com.cloudmersive.client.FilterApi;ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: ApikeyApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");Apikey.setApiKey("YOUR API KEY");// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)//Apikey.setApiKeyPrefix("Token");FilterApi apiInstance = new FilterApi();Integer levels = 56; // Integer | Number of unique colors to retain in the output imageFile imageFile = new File("/path/to/file"); // File | Image file to perform the operation on.  Common file formats such as PNG, JPEG are supported.try {byte[] result = apiInstance.filterPosterize(levels, imageFile);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling FilterApi#filterPosterize");e.printStackTrace();}

And that’s about it. Let us take a moment and look at an example result for this image:

Image for post
Image for post

Here’s the result after applying posterization with 4 unique colors:

Image for post
Image for post

Written by

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store