How to Merge Two PNG Files Together using Java

Combining two of the same file type to create a single file can be accomplished in a few different ways. If you’re looking for a way to quickly combine two PNG files within your application, we’ve got you covered. Our PNG Merge API will automatically stack two input PNG files on top of one another (taking order into account) and output a newly combined file. To take advantage of this API, refer to the demonstration below where we’ve provided ready-to-run code examples to structure your API call in Java.

Before we structure the call, let’s first install the Java SDK with Maven. Add a reference to the repository in pom.xml:

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

Then add one to the dependency:

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v4.25</version>
</dependency>
</dependencies>

Now we can go ahead and add the imports to the top of the file and structure the API call. Before doing so, make sure you have both of your input file paths and a Cloudmersive API key handy (you can get one for free by registering a free account on our website).

// 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.MergeDocumentApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: Apikey
ApiKeyAuth 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");
MergeDocumentApi apiInstance = new MergeDocumentApi();
File inputFile1 = new File("/path/to/inputfile"); // File | First input file to perform the operation on.
File inputFile2 = new File("/path/to/inputfile"); // File | Second input file to perform the operation on (more than 2 can be supplied).
try {
byte[] result = apiInstance.mergeDocumentPng(inputFile1, inputFile2);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling MergeDocumentApi#mergeDocumentPng");
e.printStackTrace();
}

Simple as that — no more code required.

--

--

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
Cloudmersive

Cloudmersive

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