How to posterize an image by reducing colors in Java

Cloudmersive
2 min readJan 29, 2020

--

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

<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>

Dependency reference

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v2.75</version>
</dependency>
</dependencies>

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:

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

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

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

No responses yet