Extract Images From Website Using C#

To extract images from a website in C#, load the page with HTMLDocument, collect <img> or icon <link> elements, read src or href attributes, resolve relative paths with BaseURI, send requests through Context.Network, and save successful responses as local image files.

Extracting page images is useful for archiving, migration, and content analysis. Aspose.HTML for .NET provides DOM APIs for locating image references and a document network service for retrieving remote or local resources.

Extract Images from Website in C#

HTML documents commonly reference images through the src attribute of <img> elements. The following example extracts these image resources. Images available only through srcset, custom lazy-loading attributes, or CSS background properties require additional handling.

To download images from a website in C#:

  1. Pass the webpage address to the HTMLDocument(string address) constructor.
  2. Use the GetElementsByTagName(“img”) method to collect all <img> elements in a live HTMLCollection.
  3. Read each src value with GetAttribute(“src”), remove empty and duplicate values, and skip embedded data URIs.
  4. Resolve each remaining src value against document.BaseURI by creating a new Url object.
  5. Create a RequestMessage for each absolute image URL and send it through document.Context.Network.Send().
  6. Check response.IsSuccess, obtain a non-empty file name from the URL path, and save the response bytes with File.WriteAllBytes().
 1// Extract images from website using C#
 2
 3// Load a webpage that contains <img> elements
 4using HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/net/tutorial/html-colors/");
 5
 6// Collect all <img> elements
 7HTMLCollection images = document.GetElementsByTagName("img");
 8
 9// Extract distinct src values and skip empty and data URI sources
10IEnumerable<string> sources = images
11    .Select(image => image.GetAttribute("src"))
12    .Where(src => !string.IsNullOrWhiteSpace(src) &&
13        !src.StartsWith("data:", StringComparison.OrdinalIgnoreCase))
14    .Distinct();
15
16foreach (string src in sources)
17{
18    // Resolve the image URL against the document base URI
19    Url imageUrl = new Url(src, document.BaseURI);
20
21    using RequestMessage request = new RequestMessage(imageUrl);
22    using ResponseMessage response = document.Context.Network.Send(request);
23
24    if (!response.IsSuccess)
25        continue;
26
27    string fileName = Path.GetFileName(imageUrl.Pathname);
28
29    if (string.IsNullOrWhiteSpace(fileName))
30        continue;
31
32    File.WriteAllBytes(Path.Combine(OutputDir, fileName), response.Content.ReadAsByteArray());
33}

After the code runs, successfully downloaded <img src> resources are available in the output directory.

Note: Before downloading or reusing images, ensure that you have the required permission and comply with applicable copyright rules and website terms.

Extract Images from a Local HTML File in C#

Aspose.HTML for .NET can load a local HTML file by passing its path to the HTMLDocument(string address) constructor. Relative image paths are resolved against document.BaseURI as file: URLs and can be retrieved through the document’s network context.

To extract images from a local .html file:

  1. Pass the local file path to the HTMLDocument(string address) constructor.
  2. Collect all <img> elements using GetElementsByTagName("img").
  3. Extract non-empty src attributes, skip data URIs, and resolve relative paths using document.BaseURI.
  4. Send each request through document.Context.Network; local resources use resolved file: URLs. Save each successful response to the output directory.
 1// Extract images from a local HTML file using C#
 2
 3// Load a local HTML file
 4using HTMLDocument document = new HTMLDocument(Path.Combine(DataDir, "nature.html"));
 5
 6// Collect all <img> elements
 7HTMLCollection images = document.GetElementsByTagName("img");
 8
 9// Create a distinct collection of relative image URLs
10IEnumerable<string> urls = images
11    .Select(element => element.GetAttribute("src"))
12    .Where(src => !string.IsNullOrWhiteSpace(src) &&
13        !src.StartsWith("data:", StringComparison.OrdinalIgnoreCase))
14    .Distinct();
15
16// Create absolute image URLs
17IEnumerable<Url> absUrls = urls.Select(src => new Url(src, document.BaseURI));
18
19foreach (Url url in absUrls)
20{
21    // Create an image request message
22    using RequestMessage request = new RequestMessage(url);
23
24    // Extract image
25    using ResponseMessage response = document.Context.Network.Send(request);
26
27    // Check whether a response is successful
28    if (response.IsSuccess)
29    {
30        // Save image to a local file system
31        string fileName = Path.GetFileName(url.Pathname);
32        if (string.IsNullOrEmpty(fileName)) fileName = "image";
33        File.WriteAllBytes(Path.Combine(OutputDir, fileName), response.Content.ReadAsByteArray());
34    }
35}

After the code runs, successfully retrieved local image resources are available in the output directory. Embedded data URI images are skipped because they must be decoded rather than requested as separate resources; see the FAQ for the distinction.

Extract Icons from Website in C#

Website icons are commonly referenced by <link> elements. Because rel is a space-separated list of tokens, an icon link may use rel="icon" or the legacy form rel="shortcut icon". Sites may also use platform-specific values such as apple-touch-icon.

To extract icons from a website in C#:

  1. Pass the webpage address to the HTMLDocument(string address) constructor.
  2. Use the GetElementsByTagName(“link”) method to collect all <link> elements.
  3. Split each rel value into tokens and keep links containing icon, apple-touch-icon, apple-touch-icon-precomposed, or mask-icon. A value such as shortcut icon is matched by its icon token.
  4. Read each href value with GetAttribute(“href”), remove empty and duplicate values, and skip data URIs.
  5. Resolve relative icon paths against document.BaseURI, then create and send a RequestMessage for each absolute URL.
  6. Check response.IsSuccess, obtain a non-empty file name from the URL path, and save the response bytes to the output directory.
 1// Download icons from website using C#
 2
 3using HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/net/message-handlers/");
 4
 5// Collect all <link> elements
 6HTMLCollection links = document.GetElementsByTagName("link");
 7
 8string[] iconTypes =
 9{
10    "icon",
11    "apple-touch-icon",
12    "apple-touch-icon-precomposed",
13    "mask-icon"
14};
15
16// Select links whose rel attribute contains an icon-related token
17IEnumerable<Element> icons = links.Where(link =>
18    link.GetAttribute("rel")
19        .Split()
20        .Any(token => iconTypes.Contains(
21            token,
22            StringComparer.OrdinalIgnoreCase)));
23
24// Extract distinct href values and skip empty and data URI sources
25IEnumerable<string> sources = icons
26    .Select(icon => icon.GetAttribute("href"))
27    .Where(href => !string.IsNullOrWhiteSpace(href) &&
28        !href.StartsWith("data:", StringComparison.OrdinalIgnoreCase))
29    .Distinct();
30
31foreach (string src in sources)
32{
33    // Resolve the icon URL against the document base URI
34    Url iconUrl = new Url(src, document.BaseURI);
35
36    using RequestMessage request = new RequestMessage(iconUrl);
37    using ResponseMessage response = document.Context.Network.Send(request);
38
39    if (!response.IsSuccess)
40        continue;
41
42    string fileName = Path.GetFileName(iconUrl.Pathname);
43
44    if (string.IsNullOrWhiteSpace(fileName))
45        continue;
46
47    File.WriteAllBytes(Path.Combine(OutputDir, fileName), response.Content.ReadAsByteArray());
48}

After the code runs, successfully downloaded icon resources are available in the output directory.

Common Mistakes and Fixes

ProblemCauseSolution
Images are not downloadedsrc attribute contains a data URI or empty stringFilter with string.IsNullOrWhiteSpace() and skip data URIs using src.StartsWith("data:", StringComparison.OrdinalIgnoreCase)
Relative URLs resolve incorrectlyA relative src or href value is used as if it were an absolute URLResolve it with new Url(value, document.BaseURI) before sending the request
Failed HTTP responses are saved as imagesThe response status is not checked before writing its contentCheck response.IsSuccess and skip unsuccessful responses
Files are overwrittenDuplicate file names from different URLsGenerate unique names (e.g., include a counter or hash of the URL)
Icons are missedExact comparison with rel="icon" misses multiple-token and specialized icon relationshipsSplit rel into tokens and match icon, apple-touch-icon, apple-touch-icon-precomposed, or mask-icon case-insensitively

FAQ

Which HTML elements are used to extract images?

Standard images are usually found in <img> elements through the src attribute. Website icons are commonly found in <link> elements through the href attribute when rel identifies an icon relationship.

Why do I need BaseURI when extracting images?

Many documents use relative image URLs. BaseURI provides the document’s absolute base URI so the examples can resolve resources referenced by either a remote webpage or a local HTML file.

Can this example download data URI images?

No. The examples skip data URI images because they are embedded directly in HTML rather than stored as separate HTTP, HTTPS, or file resources. Decode the Base64 or percent-encoded data separately when those images must also be saved.

How can I avoid overwriting files?

Generate unique local file names, for example by adding a counter, using a URL hash, or preserving part of the source path when saving images.

Other Platforms

Related Data Extraction Articles

The complete C# examples and data files are available in the Aspose.HTML for .NET GitHub repository.