How to convert an image to black and white grayscale in Java
Grayscale is an essential feature for any good photo app or website. Implementation, however, can be quite tedious to get working. There is another answer, one that I think you will like. We will let an API do the work for us. Five minutes until completion? Sounds good. Let’s get to it.
The first step is to compile our library using Jitpack by adding the following two references to our pom.xml file.
Repositories reference
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Dependencies reference
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v2.75</version>
</dependency>
</dependencies>
Now call filterBlackAndWhite, as you can see demonstrated here:
// 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();File 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.filterBlackAndWhite(imageFile);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling FilterApi#filterBlackAndWhite");e.printStackTrace();}
And just like that, you’re done! What about the results? Let’s test this out on the following image:
And here are is the result: