How to Convert a URL to PNG in Java
Our input will be the URL of the web page we want to capture, any extra loading wait, and the desired size parameters for your output.
Join the DZone community and get the full member experience.
Join For FreeWhen explaining a complex flow of operations to a colleague or client, unless you can physically aid them in person, obtaining visual depictions of each step is your best option to help walk through the process efficiently and with smaller margins for user error. Thus, screenshot images of web pages and online processes can be an invaluable resource for example documents and operational tutorials. With screenshots, you can clearly and easily lead clients and partners step-by-step to a solution.
Manually capturing and organizing these images, however, may seem a daunting task. Especially if the process you are capturing is particularly complex. Automating this process, instead, will provide you with catalogs of useful items to use in presentations, manuals, or guide sheets.
Today, I will be showing you how to take a screenshot of a webpage using a Conversion API. This process will return a full-page PNG image, with support for Javascript, HTML5, CSS, and other advanced features. Then, we can convert the PNG screenshot to any image format using our second API. By any image format, we mean that this API supports over 100 image file formats, so you can utilize your screenshots for whatever you need.
For our first function, our input will be the URL of the web page we want to capture, any extra loading wait, and the desired size parameters for your output. This will then return a PNG file according to your specifications.
The first step in our process should be installing our library with Maven, by adding a Jitpack reference to the repository in pom.xml:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Then, we can add this reference to the dependency:
xxxxxxxxxx
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v3.54</version>
</dependency>
</dependencies>
To install with Gradle, you can add this to your root build.gradle at the end of repositories:
xxxxxxxxxx
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Then, add the dependency in build.gradle:
xxxxxxxxxx
dependencies {
implementation 'com.github.Cloudmersive:Cloudmersive.APIClient.Java:v3.54'
}
After install, we need to add our imports to the top of our file and call our function:
xxxxxxxxxx
// 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.ConvertWebApi;
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");
ConvertWebApi apiInstance = new ConvertWebApi();
ScreenshotRequest input = new ScreenshotRequest(); // ScreenshotRequest | Screenshot request parameters
try {
byte[] result = apiInstance.convertWebUrlToScreenshot(input);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ConvertWebApi#convertWebUrlToScreenshot");
e.printStackTrace();
}
With your new PNG image, you can easily edit, or alter the image to meet your needs, and not worry about the loss of quality on compression. To make the screenshot more appealing on a webpage or other highly formatted medium, the PNG format will allow you to introduce transparency to the image, to better fit your theming and appeal to the viewer.
To ensure that the API functions properly, you will need to verify that:
- Your URL, load, and size input are valid
- Your API Key has been properly inserted into the code block. This can be retrieved at no cost and with no commitment on the Cloudmersive website and will provide access to 800 monthly calls across our library of APIs.
Once you have retrieved your PNG image, you can use this next function to convert it to any other image file format. For example, if the image is being placed in a document and you need to reduce the file size, you can easily compress the image to a fraction of its original dimensions. Furthermore, in a JPG image file, you can store EXIF data for easier categorization and organization.
Like with our first function, we will need to complete our library install with Maven or Gradle. Then, we will once again add our imports to the top of the file, and call our function:
xxxxxxxxxx
// 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.ConvertImageApi;
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");
ConvertImageApi apiInstance = new ConvertImageApi();
String format1 = "format1_example"; // String | Input file format as a 3+ letter file extension. You can also provide UNKNOWN for unknown file formats. Supported formats include AAI, ART, ARW, AVS, BPG, BMP, BMP2, BMP3, BRF, CALS, CGM, CIN, CMYK, CMYKA, CR2, CRW, CUR, CUT, DCM, DCR, DCX, DDS, DIB, DJVU, DNG, DOT, DPX, EMF, EPDF, EPI, EPS, EPS2, EPS3, EPSF, EPSI, EPT, EXR, FAX, FIG, FITS, FPX, GIF, GPLT, GRAY, HDR, HEIC, HPGL, HRZ, ICO, ISOBRL, ISBRL6, JBIG, JNG, JP2, JPT, J2C, J2K, JPEG/JPG, JXR, MAT, MONO, MNG, M2V, MRW, MTV, NEF, ORF, OTB, P7, PALM, PAM, PBM, PCD, PCDS, PCL, PCX, PDF, PEF, PES, PFA, PFB, PFM, PGM, PICON, PICT, PIX, PNG, PNG8, PNG00, PNG24, PNG32, PNG48, PNG64, PNM, PPM, PSB, PSD, PTIF, PWB, RAD, RAF, RGB, RGBA, RGF, RLA, RLE, SCT, SFW, SGI, SID, SUN, SVG, TGA, TIFF, TIM, UIL, VIFF, VICAR, VBMP, WDP, WEBP, WPG, X, XBM, XCF, XPM, XWD, X3F, YCbCr, YCbCrA, YUV
String format2 = "format2_example"; // String | Output (convert to this format) file format as a 3+ letter file extension. Supported formats include AAI, ART, ARW, AVS, BPG, BMP, BMP2, BMP3, BRF, CALS, CGM, CIN, CMYK, CMYKA, CR2, CRW, CUR, CUT, DCM, DCR, DCX, DDS, DIB, DJVU, DNG, DOT, DPX, EMF, EPDF, EPI, EPS, EPS2, EPS3, EPSF, EPSI, EPT, EXR, FAX, FIG, FITS, FPX, GIF, GPLT, GRAY, HDR, HEIC, HPGL, HRZ, ICO, ISOBRL, ISBRL6, JBIG, JNG, JP2, JPT, J2C, J2K, JPEG/JPG, JXR, MAT, MONO, MNG, M2V, MRW, MTV, NEF, ORF, OTB, P7, PALM, PAM, PBM, PCD, PCDS, PCL, PCX, PDF, PEF, PES, PFA, PFB, PFM, PGM, PICON, PICT, PIX, PNG, PNG8, PNG00, PNG24, PNG32, PNG48, PNG64, PNM, PPM, PSB, PSD, PTIF, PWB, RAD, RAF, RGB, RGBA, RGF, RLA, RLE, SCT, SFW, SGI, SID, SUN, SVG, TGA, TIFF, TIM, UIL, VIFF, VICAR, VBMP, WDP, WEBP, WPG, X, XBM, XCF, XPM, XWD, X3F, YCbCr, YCbCrA, YUV
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
try {
byte[] result = apiInstance.convertImageImageFormatConvert(format1, format2, inputFile);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ConvertImageApi#convertImageImageFormatConvert");
e.printStackTrace();
}
As you can see, we have listed the possible format conversions for this function within its notes. With this, you can use the image however you would like, and in whatever format you need.
Opinions expressed by DZone contributors are their own.
Comments