How to Add Image to HTML? C# Examples
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.
Add Image to HTML
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.
Add Image to an Empty HTML
If you create HTML from scratch and want to add an image, you should follow a few steps:
- Create an instance of the HTMLDocument class.
- Retrieve the
<body>
element using the GetElementsByTagName() method. - Create an
<img>
element using the CreateElement() method. - Set image attributes using the SetAttribute() method.
- Use the
AppendChild() method to insert the
<img>
element into the document’s body. - Save the modified document to a specified output directory using the Save() method.
1// Create a new HTML document
2using (HTMLDocument document = new HTMLDocument())
3{
4 // Get a reference to the <body> element
5 HTMLElement body = (HTMLElement)document.GetElementsByTagName("body").First();
6
7 // Create an <img> element
8 var img = document.CreateElement("img");
9 img.SetAttribute("src", "https://docs.aspose.com/html/images/aspose-html-for-net.png"); // Specify a link URL or local path
10 img.SetAttribute("alt", "Aspose.HTML for .NET Product Logo");
11 img.SetAttribute("width", "128"); // Set parameters optionally
12 img.SetAttribute("height", "128");
13
14 // Add the <img> element to the <body>
15 body.AppendChild(img);
16
17 // Save file to a local file system
18 document.Save(Path.Combine(OutputDir, "add-image.html"), new HTMLSaveOptions());
19}
Add Image to Existing HTML
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:
- Opens an existing HTML file using the
HTMLDocument
class. - Use the
GetElementsByTagName("p")
method to collect all<p>
elements in the HTML document and store them in anHTMLCollection
. - Ensure that at least two paragraphs exist before proceeding with modifications. The
if
statement ensures that the document contains at least two paragraph elements by verifying thatparagraphs.Length >= 2
. - Use the
CreateElement("img")
method to generate a new<img>
element and sets its src, alt, width, and height attributes. - Retrieve the second
<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. - Use the InsertBefore(img, secondParagraph.NextSibling) to place the newly created image right after the second paragraph.
- Save the modified document to a specified output directory using the
Save()
method.
1// Load an existing HTML document
2using (HTMLDocument document = new HTMLDocument(Path.Combine(DataDir, "file.html")))
3{
4 // Get all <p> (paragraph) elements
5 HTMLCollection paragraphs = document.GetElementsByTagName("p");
6
7 // Check if there are at least two paragraphs
8 if (paragraphs.Length >= 2)
9 {
10 // Create a new <img> element
11 var img = document.CreateElement("img");
12 img.SetAttribute("src", "https://docs.aspose.com/html/images/aspose-html-for-net.png"); // Set image source (URL or local path)
13 img.SetAttribute("alt", "Aspose.HTML for .NET Product Logo");
14 img.SetAttribute("width", "128");
15 img.SetAttribute("height", "128");
16
17 // Get the second paragraph
18 Element secondParagraph = paragraphs[1];
19
20 // Insert the image after the second paragraph
21 secondParagraph.ParentNode.InsertBefore(img, secondParagraph.NextSibling);
22 }
23
24 // Save the updated HTML document
25 document.Save(Path.Combine(OutputDir, "add-image-after-paragraph.html"), new HTMLSaveOptions());
26}
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 it after the second paragraph.
HTML Background Images
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 and optimized by size.
Add Background Image Using Internal CSS
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>
:
- Use the
HTMLDocument
class to load an existing HTML from the specified directory. - Call the
CreateElement()
method to create a<style>
for internal CSS. - Use the CreateTextNode() method to create a CSS rule to set the background image.
- Use the
AppendChild()
method to insert the CSS as text inside the<style>
element. - Use the
QuerySelector() to find the
<head>
element. If missing, call CreateElement() to generate a new<head>
and insert it before<body>
. - Call the
AppendChild()
method to add the<style>
element inside<head>
. - Save the modified document to a specified output directory using the
Save()
method.
1// Load an existing HTML document
2using (HTMLDocument document = new HTMLDocument(Path.Combine(DataDir, "document.html")))
3{
4 // Create a new <style> element
5 HTMLStyleElement styleElement = (HTMLStyleElement)document.CreateElement("style");
6
7 // Define CSS for background image
8 string css = "body { background-image: url('background.png'); }";
9 styleElement.AppendChild(document.CreateTextNode(css));
10
11 // Get the <head> element or create one if missing
12 HTMLElement head = document.QuerySelector("head") as HTMLElement;
13 if (head == null)
14 {
15 head = document.CreateElement("head") as HTMLElement;
16 document.DocumentElement.InsertBefore(head, document.Body);
17 }
18
19 // Append the <style> element to the <head>
20 head.AppendChild(styleElement);
21
22 // Save the updated HTML document
23 document.Save(Path.Combine(OutputDir, "add-background-image-to-entire-page.html"));
24}
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:
- background-position specifies the starting position of the background image (e.g.,
center
,top left
,50% 50%
). - background-size defines the size of the background image, allowing values like
cover
,contain
, or specific dimensions (e.g.,100px 200px
). - background-repeat determines whether the background image repeats (e.g.,
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// Load the existing HTML document
2using (HTMLDocument document = new HTMLDocument(Path.Combine(DataDir, "document-with-h1.html")))
3{
4 // Create a new <style> element
5 HTMLStyleElement styleElement = (HTMLStyleElement)document.CreateElement("style");
6
7 // Define CSS to apply a background image to all <p> elements
8 string css = "h1 { background-image: url('background.png'); background-repeat: no-repeat; padding: 60px;}";
9 styleElement.AppendChild(document.CreateTextNode(css));
10
11 // Get the <head> element or create one if missing
12 HTMLElement head = document.QuerySelector("head") as HTMLElement;
13 if (head == null)
14 {
15 head = document.CreateElement("head") as HTMLElement;
16 document.DocumentElement.InsertBefore(head, document.Body);
17 }
18
19 // Append the <style> element to the <head>
20 head.AppendChild(styleElement);
21
22 // Save the updated HTML document
23 document.Save(Path.Combine(OutputDir, "add-background-image-to-h1.html"));
24}
The figure shows a fragment of the web page - HTML file with background image for <h1>
element:
Add Background Image Using Inline CSS
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// Load an existing HTML document
2using (HTMLDocument document = new HTMLDocument(Path.Combine(DataDir, "document.html")))
3{
4 // Get the <body> element
5 HTMLElement body = document.QuerySelector("body") as HTMLElement;
6
7 if (body != null)
8 {
9 // Set a background image using inline CSS
10 body.SetAttribute("style", "background-image: url('flower.png');");
11 }
12
13 // Save the updated HTML document
14 document.Save(Path.Combine(OutputDir, "add-background-image.html"));
15}
Summary and Recommendations
- Adding images using the
<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. - The
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. - Using internal CSS (the
<style>
element) is a structured approach to setting background images, keeping the HTML cleaner and the styles centralized. Inline CSS (thestyle
attribute) is an alternative for simple cases. - Use CSS properties such as
background-size
,background-repeat
andbackground-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.
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.