How to Extract Images from a Website in Java
Aspose.HTML for Java
loads a web page into an HTMLDocument and exposes its elements through the HTML DOM. Collect the <img> elements, read each src attribute, resolve relative paths against the document base URI, and request every image through the document network service.
This process downloads the resource bytes referenced by the page; it does not convert or re-encode the images. JPEG, PNG, GIF, WebP, SVG, and other image formats remain in the form returned by the server.
Download Website Images in Java
The example opens a public web page, collects distinct src values, and saves successful responses in an images directory. Numeric prefixes prevent files with the same URL path name from overwriting one another.
Extract Images from Website in Java
Path outputDirectory = Paths.get("images");
Files.createDirectories(outputDirectory);
try (HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/java/web-accessibility-rules/")) {
// Collect distinct image sources from the HTML document
HTMLCollection images = document.getElementsByTagName("img");
Set<String> sources = new LinkedHashSet<>();
for (Element image : images) {
String source = image.getAttribute("src");
if (!source.isEmpty()) {
sources.add(source);
}
}
int imageNumber = 1;
for (String source : sources) {
// Resolve a relative source against the document base URI
Url imageUrl = new Url(source, document.getBaseURI());
RequestMessage request = new RequestMessage(imageUrl);
ResponseMessage response = document.getContext().getNetwork().send(request);
if (!response.isSuccess()) {
continue;
}
Path urlPath = Paths.get(imageUrl.getPathname());
Path name = urlPath.getFileName();
String fileName = name == null || name.toString().isEmpty()
? "image"
: name.toString();
Path outputPath = outputDirectory.resolve(imageNumber + "-" + fileName);
// Save the original response bytes
Files.write(outputPath, response.getContent().readAsByteArray());
imageNumber++;
}
}
Steps to Extract Images from HTML in Java
- Load the target page with
HTMLDocument. - Call
getElementsByTagName("img")to collect the image elements. - Read each nonempty
srcvalue and keep only distinct sources. - Resolve every relative source with
Urlanddocument.getBaseURI(). - Send a
RequestMessagefor each image and verify theResponseMessage. - Create a unique local name and write the response bytes with
Files.write().
Which Images Can Java Extract from a Website?
The example extracts network resources referenced directly by the src attribute of <img> elements. It also resolves relative paths, including paths affected by a document <base> element, before sending each request. The same request pattern can be applied to other resource URLs after they are located in the DOM or CSS.
For the complete documentation example, read Extract Images From Website in Java .
Image Extraction Considerations
- Keep the received image format. The code saves the response body without conversion. When a URL has no useful extension, inspect the response content type and assign an appropriate local name.
- Avoid filename collisions. Different image URLs can end with the same file name. The example adds a numeric prefix, but production applications can use a hash or another stable naming rule.
- Check every response. An image request can return an error page, authentication response, redirect, or unavailable resource instead of image bytes.
- Plan for large resources.
readAsByteArray()buffers the complete image in memory. Use a streaming strategy when pages can reference large files or many images. - Validate untrusted sources. Restrict allowed schemes and hosts when the page URL or image paths come from users, and save files only inside an approved directory.
- Respect copyright and website terms. Extract and reuse only images that you own or are authorized to access. Public availability does not grant permission to copy, redistribute, or use an image commercially.
FAQ
1. How can Java extract lazy-loaded and responsive images from HTML?
Inspect src, srcset, and <picture><source> elements, together with page-specific attributes such as data-src that store deferred image URLs. Resolve every selected URL against the document base URI before requesting the image resource.
2. How can Java extract CSS background images from a website?
Inspect external stylesheets and inline style attributes for background-image declarations. Resolve each CSS url() value against its stylesheet or document base URL, then request and save the referenced resource separately.
3. Does extracting website images preserve JPEG, PNG, GIF, WebP, or SVG files?
Writing the downloaded response bytes without re-encoding preserves the image format returned by the server. If the resource URL does not contain a reliable extension, use the response content type to choose the local file name.
4. Can Aspose.HTML for Java extract website icons?
Website icons are commonly referenced by <link> elements whose rel value contains icon. Collect those elements, read their href attributes, resolve relative URLs, and download the resources through the document network service.
Install Aspose.HTML for Java
Add Aspose.HTML for Java from the official Aspose repository. Replace ASPOSE_HTML_VERSION with an exact version from the
Aspose.HTML for Java releases
page, then reload or rebuild the project so the dependency is resolved.
Add the repository and dependency to the Maven project:
Maven – pom.xml
<repositories>
<repository>
<id>AsposeJavaAPI</id>
<url>https://releases.aspose.com/java/repo/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-html</artifactId>
<version>ASPOSE_HTML_VERSION</version>
</dependency>
</dependencies>Add the repository and dependency to the Gradle project:
Gradle – build.gradle
repositories {
maven {
url = uri('https://releases.aspose.com/java/repo/')
}
}
dependencies {
implementation 'com.aspose:aspose-html:ASPOSE_HTML_VERSION'
}Use a JDK compatible with the selected release. For manual JAR installation, Kotlin DSL, updates, and dependency troubleshooting, see Install Aspose.HTML for Java .
Related Java Data Extraction Tasks
Continue with URL downloads, SVG extraction, the data extraction hub, or the Aspose.HTML for Java API overview.