Image Converter

FREEMIUM
By petadata | Updated a month ago | Video, Images
Popularity

8.3 / 10

Latency

739ms

Service Level

100%

Health Check

N/A

Back to All Tutorials (5)

Convert Any Image to WebP by using Java

In this tutorial we will cover how to implement asynchronous approach of Image Converter. You only need to send source image to SubmitWebPConversionTask or any other submission API methods like SubmitBmpConversionTask, SubmitDicomConversionTask etc. to receive task identifier as response.

After receiving task identifier you need to check task status by calling GetConversionTaskStatus method. You need to call same method after a few seconds delay as long as task status equals to “Waiting”. Once you receive “Completed” from GetConversionTaskStatus method you can call DownloadResult method to download final image. We have used Apache HTTP Client libraries in this tutorial. You can add dependencies below in your pom.xml file.

<dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpclient</artifactId>
     <version>4.5.13</version>
</dependency>

<dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpmime</artifactId>
     <version>4.5.13</version>
</dependency>

<dependency>
     <groupId>commons-io</groupId>
     <artifactId>commons-io</artifactId>
     <version>2.11.0</version>
</dependency>

You can use the Java implementation below.

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class ImageConverter {
    private static String submitWebPConversionTask(CloseableHttpClient httpClient, String filePathToConvert, String rapidApiKey) throws IOException {
        File fileToConvert = new File(filePathToConvert);
        HttpPost submitPDFConversionTaskPost = new HttpPost("https://image-converter4.p.rapidapi.com/submitWebPConversionTask");
        submitPDFConversionTaskPost.addHeader("X-RapidAPI-Key", rapidApiKey);
        byte[] bytes = FileUtils.readFileToByteArray(fileToConvert);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, fileToConvert.getName());
        builder.addTextBody("lossy", "true", ContentType.TEXT_PLAIN);

        HttpEntity requestEntity = builder.build();
        submitPDFConversionTaskPost.setEntity(requestEntity);
        HttpResponse response = httpClient.execute(submitPDFConversionTaskPost);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw  new IOException("Cannot post conversion task");
        }

        HttpEntity responseEntity = response.getEntity();
        return EntityUtils.toString(responseEntity, "UTF-8");
    }

    private static String getConversionTaskStatus(CloseableHttpClient httpClient, String taskId, String rapidApiKey) throws IOException {
        HttpGet getConversionTaskStatus = new HttpGet("https://image-converter4.p.rapidapi.com/getConversionTaskStatus?taskId=" + taskId);
        getConversionTaskStatus.addHeader("X-RapidAPI-Key", rapidApiKey);

        HttpResponse response = httpClient.execute(getConversionTaskStatus);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw  new IOException("Cannot get conversion task status");
        }

        HttpEntity responseEntity = response.getEntity();
        return EntityUtils.toString(responseEntity, "UTF-8");
    }

    private static byte[] downloadResult(CloseableHttpClient httpClient, String taskId, String rapidApiKey) throws IOException {
        HttpGet downloadResult = new HttpGet("https://image-converter4.p.rapidapi.com/downloadResult?taskId=" + taskId);
        downloadResult.addHeader("X-RapidAPI-Key", rapidApiKey);

        HttpResponse response = httpClient.execute(downloadResult);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw  new IOException("Cannot get converted file");
        }

        HttpEntity responseEntity = response.getEntity();
        return EntityUtils.toByteArray(responseEntity);
    }

    public static void main(String[] args) throws Exception {
        String rapidApiKey = "<YOUR RAPIDAPI KEY HERE>";
        String filePathToConvert = "<IMAGE PATH TO CONVERT>";

        CloseableHttpClient httpClient = HttpClients.createDefault();
        String taskId = submitWebPConversionTask(httpClient, filePathToConvert, rapidApiKey);
        int retryCount = 0;
        while (retryCount < 100)
        {
            retryCount++;
            Thread.sleep(5000);
            String status = getConversionTaskStatus(httpClient, taskId, rapidApiKey);
            if (status.equals("Completed"))
            {
                byte[] fileBytes = downloadResult(httpClient, taskId, rapidApiKey);
                File outputFile =new File("final_image.webp");
                Files.write(outputFile.toPath(), fileBytes);
                break;
            }
            else if (status.equals("Waiting"))
            {
                continue;
            }
            else if (status.equals("Failed"))
            {
                throw new Exception("Cannot convert image");
            }
            else
            {
                throw new Exception("Invalid status");
            }
        }
    }
}