Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
If web pages contained only text, they would lack visual appeal and would fail to engage users effectively. Images and other media elements enhance the user experience by making content more engaging, interactive, and easier to understand.
In this article, we will use C# examples to show different ways to insert an image in HTML using Aspose.HTML for .NET library.
For basic information with HTML examples on how to add images to HTML using <img> tag, CSS backgrounds, JavaScript, and Base64 encoding, please visit the
Add Image to HTML – From Basic Syntax to Advanced Techniques article.
Using the HTMLDocument class, you can create an <img> element, set attributes such as src, alt, width and height, and add it to the HTML document, placing it where you want.
If you create HTML from scratch and want to add an image, you should follow a few steps:
<body> element using the
GetElementsByTagName() method.<img> element using the
CreateElement() method.<img> element into the document’s body. 1// Add image to HTML using C#
2
3// Create a new HTML document
4using (HTMLDocument document = new HTMLDocument())
5{
6 // Get a reference to the <body> element
7 HTMLElement body = (HTMLElement)document.GetElementsByTagName("body").First();
8
9 // Create an <img> element
10 var img = document.CreateElement("img");
11 img.SetAttribute("src", "https://docs.aspose.com/html/images/aspose-html-for-net.png"); // Specify a link URL or local path
12 img.SetAttribute("alt", "Aspose.HTML for .NET Product Logo");
13 img.SetAttribute("width", "128"); // Set parameters optionally
14 img.SetAttribute("height", "128");
15
16 // Add the <img> element to the <body>
17 body.AppendChild(img);
18
19 // Save file to a local file system
20 document.Save(Path.Combine(OutputDir, "add-image.html"), new HTMLSaveOptions());
21}You can insert an image by placing it in the HTML’s desired location. The following C# example shows how to add the image after the second <p> element:
HTMLDocument class.GetElementsByTagName("p") method to collect all <p> elements in the HTML document and store them in an HTMLCollection.if statement ensures that the document contains at least two paragraph elements by verifying that paragraphs.Length >= 2.CreateElement("img") method to generate a new <img> element and sets its src, alt, width, and height attributes.<p> element (paragraphs[1]) from the collection. Since collections in C# use zero-based indexing, paragraphs[1] refers to the second <p> element in the document.Save() method. 1// Add image to existing HTML using C#
2
3// Load an existing HTML document
4using (HTMLDocument document = new HTMLDocument(Path.Combine(DataDir, "file.html")))
5{
6 // Get all <p> (paragraph) elements
7 HTMLCollection paragraphs = document.GetElementsByTagName("p");
8
9 // Check if there are at least two paragraphs
10 if (paragraphs.Length >= 2)
11 {
12 // Create a new <img> element
13 var img = document.CreateElement("img");
14 img.SetAttribute("src", "https://docs.aspose.com/html/images/aspose-html-for-net.png"); // Set image source (URL or local path)
15 img.SetAttribute("alt", "Aspose.HTML for .NET Product Logo");
16 img.SetAttribute("width", "128");
17 img.SetAttribute("height", "128");
18
19 // Get the second paragraph
20 Element secondParagraph = paragraphs[1];
21
22 // Insert the image after the second paragraph
23 secondParagraph.ParentNode.InsertBefore(img, secondParagraph.NextSibling);
24 }
25
26 // Save the updated HTML document
27 document.Save(Path.Combine(OutputDir, "add-image-after-paragraph.html"), new HTMLSaveOptions());
28}This C# code loads an existing HTML file, retrieves all <p> elements, and checks if there are at least two. If so, it creates a new <img> element, sets its src, alt, width, and height attributes, and inserts this image after the second paragraph.
To insert an image as a background in HTML is easy with the CSS background-image property. There are several ways to set the value of this property. You can use inline, internal, or external CSS, and images can be PNG, JPG, GIF, or WebP formats.
If you want to add a background image to the entire web page, you can set the CSS background-image property on the <body> element within the <style> element. By default, a background image will repeat if it is smaller than the specified element, in this case, the <body> element:
1<head>
2 <style>
3 body {
4 background-image: url("background.png");
5 }
6 </style>
7</head>The following C# code allows you to add a background image to the entire page using internal CSS. It creates a <style> element into the document’s <head> with a CSS rule that sets a background image for the <body>:
HTMLDocument class to load an existing HTML from the specified directory.CreateElement() method to create a <style> for internal CSS.AppendChild() method to insert the CSS as text inside the <style> element.<head> element. If missing, call CreateElement() to generate a new <head> and insert it before <body>.AppendChild() method to add the <style> element inside <head>.Save() method. 1// Add a background image to HTML using C#
2
3// Load an existing HTML document
4using (HTMLDocument document = new HTMLDocument(Path.Combine(DataDir, "document.html")))
5{
6 // Create a new <style> element
7 HTMLStyleElement styleElement = (HTMLStyleElement)document.CreateElement("style");
8
9 // Define CSS for background image
10 string css = "body { background-image: url('background.png'); }";
11 styleElement.AppendChild(document.CreateTextNode(css));
12
13 // Get the <head> element or create one if missing
14 HTMLElement head = document.QuerySelector("head") as HTMLElement;
15 if (head == null)
16 {
17 head = document.CreateElement("head") as HTMLElement;
18 document.DocumentElement.InsertBefore(head, document.Body);
19 }
20
21 // Append the <style> element to the <head>
22 head.AppendChild(styleElement);
23
24 // Save the updated HTML document
25 document.Save(Path.Combine(OutputDir, "add-background-image-to-entire-page.html"));
26}The figure shows a fragment of the web page with background image for the entire page. The image is repeated to fill the whole screen:

Note: When using the background-image property, the background image will repeat by default if it is smaller than the container for the specified element, in this case, the <body> element. You can control the positioning of a background image and adjust its scaling using various CSS properties:
center, top left, 50% 50%).cover, contain, or specific dimensions (e.g., 100px 200px).repeat, no-repeat, repeat-x, repeat-y).These properties help ensure the background image appears correctly across different screen sizes and layouts.
Add background image to HTML element
Let’s consider the case of adding a background image for a separate HTML element, for example – for the h1 element. To prevent the background image from repeating, we specify the background-repeat property.
1// Apply background image to heading <h1> with C# and CSS
2
3// Load the existing HTML document
4using (HTMLDocument document = new HTMLDocument(Path.Combine(DataDir, "document-with-h1.html")))
5{
6 // Create a new <style> element
7 HTMLStyleElement styleElement = (HTMLStyleElement)document.CreateElement("style");
8
9 // Define CSS to apply a background image to all <p> elements
10 string css = "h1 { background-image: url('background.png'); background-repeat: no-repeat; padding: 60px;}";
11 styleElement.AppendChild(document.CreateTextNode(css));
12
13 // Get the <head> element or create one if missing
14 HTMLElement head = document.QuerySelector("head") as HTMLElement;
15 if (head == null)
16 {
17 head = document.CreateElement("head") as HTMLElement;
18 document.DocumentElement.InsertBefore(head, document.Body);
19 }
20
21 // Append the <style> element to the <head>
22 head.AppendChild(styleElement);
23
24 // Save the updated HTML document
25 document.Save(Path.Combine(OutputDir, "add-background-image-to-h1.html"));
26}The figure shows a fragment of the web page – HTML file with background image for <h1> element:

The following shows how to add a background image to a <body> element using inline CSS – the style attribute with the background-image CSS property inside the <body> element:
1<body style="background-image: url('flower.png');"> Content of the document body </body> 1// Add background image with CSS in C#
2
3// Load an existing HTML document
4using (HTMLDocument document = new HTMLDocument(Path.Combine(DataDir, "document.html")))
5{
6 // Get the <body> element
7 HTMLElement body = document.QuerySelector("body") as HTMLElement;
8
9 if (body != null)
10 {
11 // Set a background image using inline CSS
12 body.SetAttribute("style", "background-image: url('flower.png');");
13 }
14
15 // Save the updated HTML document
16 document.Save(Path.Combine(OutputDir, "add-background-image.html"));
17}<img> tag or background images via CSS visually and structurally enhances web content. Choose the appropriate way depending on whether the image is decorative or essential to the content.HTMLDocument class provides flexibility for dynamic editing of HTML content. Always check if required elements (head, body, p, etc.) exist before modifying them, for example by adding CSS properties.<style> element) is a structured approach to setting background images, keeping the HTML cleaner and the styles centralized. Inline CSS (the style attribute) is an alternative for simple cases.background-size, background-repeat and background-position to ensure images adjust well to different screen sizes.See also
In the
Add Image to HTML – From Basic Syntax to Advanced Techniques article, you will learn about different methods for adding images, including using the <img> tag, CSS background images, JavaScript, and Base64 encoding.
The article Edit HTML Document gives you basic information on how to read or modify the Document Object Model (DOM). You’ll explore how to create an HTML Element and how to work with it using Aspose.HTML for .NET.
Aspose.HTML offers free HTML Web Applications that are an online collection of converters, mergers, SEO tools, HTML code generators, URL tools, and more. The applications work on any operating system with a web browser and do not require any additional software installation. It’s a fast and easy way to efficiently and effectively solve your HTML-related tasks.
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.