Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
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.
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#:
<img> elements in a live HTMLCollection.src value with
GetAttribute(“src”), remove empty and duplicate values, and skip embedded data URIs.src value against
document.BaseURI by creating a new
Url object.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.
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:
HTMLDocument(string address) constructor.<img> elements using GetElementsByTagName("img").src attributes, skip data URIs, and resolve relative paths using document.BaseURI.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.
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#:
<link> elements.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.href value with
GetAttribute(“href”), remove empty and duplicate values, and skip data URIs.document.BaseURI, then create and send a RequestMessage for each absolute URL.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.
| Problem | Cause | Solution |
|---|---|---|
| Images are not downloaded | src attribute contains a data URI or empty string | Filter with string.IsNullOrWhiteSpace() and skip data URIs using src.StartsWith("data:", StringComparison.OrdinalIgnoreCase) |
| Relative URLs resolve incorrectly | A relative src or href value is used as if it were an absolute URL | Resolve it with new Url(value, document.BaseURI) before sending the request |
| Failed HTTP responses are saved as images | The response status is not checked before writing its content | Check response.IsSuccess and skip unsuccessful responses |
| Files are overwritten | Duplicate file names from different URLs | Generate unique names (e.g., include a counter or hash of the URL) |
| Icons are missed | Exact comparison with rel="icon" misses multiple-token and specialized icon relationships | Split rel into tokens and match icon, apple-touch-icon, apple-touch-icon-precomposed, or mask-icon case-insensitively |
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.
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.
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.
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.
The complete C# examples and data files are available in the Aspose.HTML for .NET GitHub repository.
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.