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.

Web developers, designers, researchers, journalists, and students often need to collect images from web pages for analysis, archiving, migration, or personal research. Downloading images manually takes time because each image URL must be found, resolved, requested, and saved. Aspose.HTML for .NET helps automate this workflow and extract images from a website programmatically.

Extract Images from Website in C#

Most pictures in an HTML document are represented using the <img> element. Here is an example of how to use Aspose.HTML for .NET to find images specified by this element. To download images from a website in C#:

  1. Use the HTMLDocument(Url) constructor to create an instance of the HTMLDocument class and pass it the URL of the website from which you want to find images.
  2. Use the GetElementsByTagName(“img”) method to collect all <img> elements. The method returns a list of the HTML document’s <img> elements.
  3. Use the Select() method to create a distinct collection of relative image URLs and the GetAttribute(“src”) method to extract the src attribute of each <img> element.
  4. Create absolute image URLs using the Url class and the BaseURI property of the HTMLDocument class.
  5. For each absolute URL, create a request using the RequestMessage(url) constructor.
  6. Use the document’s Context.Network.Send(request) method to send the request. The response is checked to ensure it was successful.
  7. Finally, if the response was successful, use the File.WriteAllBytes() method to save each image to a local file.
 1// Extract images from website using C#
 2
 3// Open a document you want to download images from
 4using HTMLDocument document = new HTMLDocument("https://docs.aspose.com/svg/net/drawing-basics/svg-shapes/");
 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.Select(element => element.GetAttribute("src")).Distinct();
11
12// Create absolute image URLs
13IEnumerable<Url> absUrls = urls.Select(src => new Url(src, document.BaseURI));
14
15foreach (Url url in absUrls)
16{
17    // Create an image request message
18    using RequestMessage request = new RequestMessage(url);
19
20    // Extract image
21    using ResponseMessage response = document.Context.Network.Send(request);
22
23    // Check whether a response is successful
24    if (response.IsSuccess)
25    {
26        // Save image to a local file system
27        File.WriteAllBytes(Path.Combine(OutputDir, url.Pathname.Split('/').Last()), response.Content.ReadAsByteArray());
28    }
29}

Note: It is important to adhere to copyright laws and obtain proper permission or licensing before using saved images for commercial purposes. We do not support data extraction and use of other people’s files for commercial purposes without their permission.

Extract Icons from Website in C#

Icons are a kind of image in HTML documents that are specified using <link> elements with the rel attribute set to icon. Let’s look at how to extract icons from a website using the Aspose.HTML for .NET library:

  1. Use the HTMLDocument(Url) constructor to create an instance of the HTMLDocument class and pass it the URL of the website from which you want to extract icons.
  2. Use the GetElementsByTagName(“link”) method to collect all <link> elements.
  3. To filter out non-icon images, use the Where() method that filters the collection based on the link => link.GetAttribute("rel") == "icon" expression. Thus, the icons collection will contain only links with a rel attribute with the value icon.
  4. Use the Select() method to create a distinct collection of relative icon URLs and the GetAttribute(“href”) method to extract the href attribute of each <link> element.
  5. Create absolute icon URLs using the Url class and the BaseURI property of the HTMLDocument class.
  6. Then, for each absolute URL, create a request using the RequestMessage class.
  7. Use the document’s Context.Network.Send(request) method to send the request. The response is checked to ensure it was successful.
  8. If the response was successful, use the File.WriteAllBytes() method to save icons to a local file. As a result, you will have a collection of website icons in your local folder.
 1// Download icons from website using C#
 2
 3// Open a document you want to download icons from
 4using HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/net/message-handlers/");
 5
 6// Collect all <link> elements
 7HTMLCollection links = document.GetElementsByTagName("link");
 8
 9// Leave only "icon" elements
10IEnumerable<Element> icons = links.Where(link => link.GetAttribute("rel") == "icon");
11
12// Create a distinct collection of relative icon URLs
13IEnumerable<string> urls = icons.Select(icon => icon.GetAttribute("href")).Distinct();
14
15// Create absolute icon URLs
16IEnumerable<Url> absUrls = urls.Select(src => new Url(src, document.BaseURI));
17
18foreach (Url url in absUrls)
19{
20    // Create a downloading request
21    using RequestMessage request = new RequestMessage(url);
22
23    // Extract icon
24    using ResponseMessage response = document.Context.Network.Send(request);
25
26    // Check whether a response is successful
27    if (response.IsSuccess)
28    {
29        // Save icon to a local file system
30        File.WriteAllBytes(Path.Combine(OutputDir, url.Pathname.Split('/').Last()), response.Content.ReadAsByteArray());
31    }
32}

You can use these C# examples to automate extracting images from a website for archiving, research, web content analysis, or other personal-use workflows. For designers and developers, the same workflow helps collect page assets without manually digging through source markup.

Common Mistakes and Fixes

ProblemCauseSolution
Images are not downloadedsrc attribute contains a data URI or empty stringSkip data URIs (src.StartsWith("data:")) and filter out empty values before downloading
Relative URLs resolve incorrectlyBaseURI is missing or the page uses <base> tagUse document.BaseURI or read the <base> element and combine it with the relative path
HTTP errors (404/403) stop the scriptNo error handling around Network.SendCheck response.IsSuccess and continue the loop on failure
Files are overwrittenDuplicate file names from different URLsGenerate unique names (e.g., include a counter or hash of the URL)
Icons are missedrel can contain multiple values like "shortcut icon", so == "icon" fails.Split rel by spaces and check if it contains "icon". Also match "shortcut" or "apple-touch-icon" if needed.

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 contains icon-related values.

Why do I need BaseURI when extracting images?

Many pages use relative image URLs. BaseURI helps resolve those relative paths against the loaded document URL before sending download requests.

Can this example download data URI images?

Data URI images are embedded directly in the HTML and should be handled separately from HTTP or HTTPS image URLs. Filter them out before sending network requests.

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.