DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert Files to Thumbnail Images in Java
  • Understanding Floating-Point Precision Issues in Java
  • How To Convert Common Documents to PNG Image Arrays in Java
  • How To Convert ODF Files to PDF in Java

Trending

  • How the Go Runtime Preempts Goroutines for Efficient Concurrency
  • Unlocking AI Coding Assistants Part 2: Generating Code
  • Java’s Next Act: Native Speed for a Cloud-Native World
  • A Guide to Developing Large Language Models Part 1: Pretraining
  1. DZone
  2. Coding
  3. Java
  4. How to Convert a URL to PNG in Java

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.

By 
Brian O'Neill user avatar
Brian O'Neill
DZone Core CORE ·
Oct. 21, 20 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
5.1K Views

Join the DZone community and get the full member experience.

Join For Free

When 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:

XML
 




x


 
1
<repositories>
2
    <repository>
3
        <id>jitpack.io</id>
4
        <url>https://jitpack.io</url>
5
    </repository>
6
</repositories>



Then, we can add this reference to the dependency:

XML
 




xxxxxxxxxx
1


 
1
<dependencies>
2
<dependency>
3
    <groupId>com.github.Cloudmersive</groupId>
4
    <artifactId>Cloudmersive.APIClient.Java</artifactId>
5
    <version>v3.54</version>
6
</dependency>
7
</dependencies>



To install with Gradle, you can add this to your root build.gradle at the end of repositories:

Java
 




xxxxxxxxxx
1


 
1
allprojects {
2
    repositories {
3
        ...
4
        maven { url 'https://jitpack.io' }
5
    }
6
}



Then, add the dependency in build.gradle:

Java
 




xxxxxxxxxx
1


 
1
dependencies {
2
        implementation 'com.github.Cloudmersive:Cloudmersive.APIClient.Java:v3.54'
3
}



After install, we need to add our imports to the top of our file and call our function:

Java
 




xxxxxxxxxx
1
24


 
1
// Import classes:
2
//import com.cloudmersive.client.invoker.ApiClient;
3
//import com.cloudmersive.client.invoker.ApiException;
4
//import com.cloudmersive.client.invoker.Configuration;
5
//import com.cloudmersive.client.invoker.auth.*;
6
//import com.cloudmersive.client.ConvertWebApi;
7

          
8
ApiClient defaultClient = Configuration.getDefaultApiClient();
9

          
10
// Configure API key authorization: Apikey
11
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
12
Apikey.setApiKey("YOUR API KEY");
13
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
14
//Apikey.setApiKeyPrefix("Token");
15

          
16
ConvertWebApi apiInstance = new ConvertWebApi();
17
ScreenshotRequest input = new ScreenshotRequest(); // ScreenshotRequest | Screenshot request parameters
18
try {
19
    byte[] result = apiInstance.convertWebUrlToScreenshot(input);
20
    System.out.println(result);
21
} catch (ApiException e) {
22
    System.err.println("Exception when calling ConvertWebApi#convertWebUrlToScreenshot");
23
    e.printStackTrace();
24
}



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:

Java
 




xxxxxxxxxx
1
26


 
1
// Import classes:
2
//import com.cloudmersive.client.invoker.ApiClient;
3
//import com.cloudmersive.client.invoker.ApiException;
4
//import com.cloudmersive.client.invoker.Configuration;
5
//import com.cloudmersive.client.invoker.auth.*;
6
//import com.cloudmersive.client.ConvertImageApi;
7

          
8
ApiClient defaultClient = Configuration.getDefaultApiClient();
9

          
10
// Configure API key authorization: Apikey
11
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
12
Apikey.setApiKey("YOUR API KEY");
13
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
14
//Apikey.setApiKeyPrefix("Token");
15

          
16
ConvertImageApi apiInstance = new ConvertImageApi();
17
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
18
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
19
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
20
try {
21
    byte[] result = apiInstance.convertImageImageFormatConvert(format1, format2, inputFile);
22
    System.out.println(result);
23
} catch (ApiException e) {
24
    System.err.println("Exception when calling ConvertImageApi#convertImageImageFormatConvert");
25
    e.printStackTrace();
26
}



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.

Java (programming language) Convert (command)

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert Files to Thumbnail Images in Java
  • Understanding Floating-Point Precision Issues in Java
  • How To Convert Common Documents to PNG Image Arrays in Java
  • How To Convert ODF Files to PDF in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!