Extract Images from HTML with a .NET API
Aspose.HTML for .NET
loads a local file or webpage into an
HTMLDocument
. A C# application can collect <img> elements, read each src attribute, resolve relative references against the document base URI, and download the referenced image resources through the document network service.
Download Images Referenced by an HTML File
The following example reads input.html, finds distinct non-empty image sources, skips embedded data URIs, and saves each successfully retrieved file in an output directory. A numeric prefix prevents files with the same name from overwriting one another.
C# Code to Extract Images from HTML
using Aspose.Html;
using Aspose.Html.Collections;
using Aspose.Html.Net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
string outputDirectory = Path.Combine("Output", "images");
Directory.CreateDirectory(outputDirectory);
// Load a local HTML file
using HTMLDocument document = new HTMLDocument("input.html");
// Collect distinct image sources and skip embedded data URIs
HTMLCollection images = document.GetElementsByTagName("img");
IEnumerable<string> sources = images
.Select(image => image.GetAttribute("src"))
.Where(src => !string.IsNullOrWhiteSpace(src) &&
!src.StartsWith("data:", StringComparison.OrdinalIgnoreCase))
.Distinct();
int imageNumber = 1;
foreach (string src in sources)
{
// Resolve relative references against the document base URI
Url imageUrl = new Url(src, document.BaseURI);
using RequestMessage request = new RequestMessage(imageUrl);
using ResponseMessage response = document.Context.Network.Send(request);
if (!response.IsSuccess)
continue;
string fileName = Path.GetFileName(imageUrl.Pathname);
if (string.IsNullOrWhiteSpace(fileName))
continue;
string outputPath = Path.Combine(
outputDirectory,
$"{imageNumber++}-{fileName}");
File.WriteAllBytes(outputPath, response.Content.ReadAsByteArray());
}
Steps to Extract Images from HTML in C#
- Load the local HTML file or webpage with an
HTMLDocument. - Call
GetElementsByTagName("img")to collect the document’s<img>elements. - Read each
srcattribute withGetAttribute(), then discard empty values, duplicates, and embedded data URIs. - Create a
Urlfrom each source anddocument.BaseURIso relative paths resolve correctly. - Send a
RequestMessagethroughdocument.Context.Networkand checkresponse.IsSuccess. - Read the response bytes and save each image under a unique local file name.
Plan a Reliable Image Extraction Workflow
- Define the discovery scope. Decide which HTML elements, attributes, styles, and dynamically populated values belong to the extraction task before collecting resource references.
- Separate discovery from retrieval. First build and normalize the resource list, then retrieve each unique item. This makes filtering, deduplication, logging, and retry handling easier to control.
- Validate every response. Check the response status and content before writing bytes. A URL can return an error page, redirect, empty response, or content that is not an image.
- Sanitize output paths. Do not use an untrusted URL path directly as a local path. Create safe file names and ensure every destination remains inside the intended output directory.
- Keep a source-to-file map. Record the original absolute resource address and its saved file name when the application must update HTML references or audit the extracted files later.
- Configure network behavior. Authentication, request headers, filtering, proxies, timeouts, and retries belong to the network layer rather than DOM selection.
- Confirm reuse rights. Downloading a publicly reachable image does not grant permission to republish it. Follow the source site’s terms and applicable copyright requirements.
For broader element selection, see the
CSS Selector
and
XPath Query
workflows. To create an <img> element rather than download its resource, use the
HTML Image Code Generator
.
Image Extraction Documentation and API Reference
Read
Extract Images from Website
for separate examples covering webpages, local HTML files, and website icons. The
HTMLCollection
reference describes the collection returned for matching elements, while
ResponseMessage
exposes the status, headers, and content returned by the document network service.
Get Started with Aspose.HTML for .NET API
Install Aspose.HTML for .NET from NuGet with the .NET CLI:
dotnet add package Aspose.HTML
You can also use the NuGet Package Manager UI or run Install-Package Aspose.HTML in the Package Manager Console. See the
installation guide
for setup details, or request a
temporary license
to evaluate the API without evaluation limitations.
Extract Images from HTML FAQ
1. Can I extract images from both an HTML file and a webpage?
Yes. HTMLDocument can load a local HTML file or an HTTP or HTTPS address. After loading the document, collect its image sources, resolve their URLs, and save the returned resource data.
2. How are relative image URLs resolved when extracting images?
Resolve each relative src against HTMLDocument.BaseURI. The base URI represents the location of the loaded file or webpage and produces the absolute URL required to retrieve the image.
3. How do I extract Base64 images from HTML?
Read the data URI from the src attribute, separate its media type and encoded payload, and decode the payload before saving the bytes. A data URI is embedded content, so it should not be downloaded as an external resource.
4. Why are some webpage images missing from the extracted files?
A page may load images through srcset, <picture> sources, CSS backgrounds, scripts, or custom lazy-loading attributes rather than <img src>. Inspect those sources separately when the extraction must cover them.
5. How do I avoid overwriting images that have the same file name?
Assign a unique output name to every resource. Add a sequence number, retain part of the source path, or append a hash of the absolute URL before saving the image.
Related HTML Image Workflows
Continue with another image or HTML resource task.