如何在 HTML 中添加图像 – C# 示例

如果网页只包含文字,就会缺乏视觉吸引力,无法有效吸引用户。图片和其他媒体元素能使内容更吸引人、更具互动性、更易于理解,从而增强用户体验。

在本文中,我们将使用 C# 示例来展示使用 Aspose.HTML for .NET 库在 HTML 中插入图片的不同方法。

有关如何使用 <img> 标记、CSS 背景、JavaScript 和 Base64 编码在 HTML 中添加图片的基本信息和 HTML 示例,请访问 在 HTML 中添加图片 – 从基本语法到高级技巧 文章。

在 HTML 中添加图像

使用 HTMLDocument 类,您可以创建一个 <img> 元素,设置属性(如 srcaltwidthheight),并将其添加到 HTML 文档中,放置在您想要的位置。

为空 HTML 添加图片

如果要从头开始创建 HTML 并添加图片,应遵循以下几个步骤:

  1. 创建 HTMLDocument 类的实例。
  2. 使用 GetElementsByTagName() 方法读取 <body> 元素。
  3. 使用 CreateElement() 方法创建一个 <img> 元素。
  4. 使用 SetAttribute() 方法设置图像属性。
  5. 使用 AppendChild() 方法将 <img> 元素插入文档正文。
  6. 使用 Save() 方法将修改后的文档保存到指定的输出目录。
 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}

在现有 HTML 中添加图像

您可以通过将图片放置在 HTML 所需位置来插入图片。下面的 C# 示例展示了如何在第二个 <p> 元素后添加图片:

  1. 使用 HTMLDocument 类打开现有的 HTML 文件。
  2. 使用 GetElementsByTagName("p") 方法收集 HTML 文档中的所有<p>元素,并将它们存储到 HTMLCollection 中。 2.在继续修改之前,确保至少有两个段落存在。if 语句通过验证 paragraphs.Length >= 2,确保文档至少包含两个段落元素。
  3. 使用 CreateElement("img") 方法生成一个新的 <img> 元素,并设置其 srcaltwidthheight 属性。 4.从集合中读取第二个 <p> 元素(paragraph[1])。由于 C# 中的集合使用基于零的索引,因此 paragraphs[1] 指的是文档中的第二个 <p> 元素。
  4. 使用 InsertBefore(img,secondParagraph.NextSibling) 将新创建的图像放在第二段之后。
  5. 使用 Save() 方法将修改后的文档保存到指定的输出目录。
 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}

这段 C# 代码会加载一个现有的 HTML 文件,检索所有的 <p> 元素,并检查是否至少有两个。如果有,则创建一个新的 <img> 元素,设置其 srcaltwidthheight 属性,并在第二段后插入该图片。

HTML 背景图片

使用 CSS 的 background-image 属性,可以很容易地在 HTML 中插入图片作为背景。有几种方法可以设置该属性的值。您可以使用内联、内部或外部 CSS,图片可以是 PNG、JPG、GIF 或 WebP 格式。

使用内部 CSS 添加背景图片

如果要为整个网页添加背景图片,可以在 <style> 元素内的 <body> 元素上设置 CSS background-image 属性。默认情况下,如果背景图片小于指定元素(本例中为 <body>元素),则会重复显示:

1<head>
2    <style>
3        body {
4			background-image: url("background.png");
5		}
6    </style>
7</head>

以下 C# 代码允许您使用内部 CSS 为整个页面添加背景图片。它在文档的<head>中创建了一个<style>元素,其中的 CSS 规则为<body>设置了背景图像:

  1. 使用 HTMLDocument 类从指定目录加载现有 HTML。
  2. 调用 CreateElement() 方法为内部 CSS 创建一个 <style>
  3. 使用 CreateTextNode() 方法创建 CSS 规则来设置背景图像。
  4. 使用AppendChild()方法将 CSS 作为文本插入<style>元素中。
  5. 使用 QuerySelector() 查找 <head> 元素。如果缺少,请调用 CreateElement() 生成一个新的 <head> 并插入到 <body> 之前。
  6. 调用 AppendChild() 方法将 <style> 元素添加到 <head> 内。
  7. 使用 Save() 方法将修改后的文档保存到指定的输出目录。
 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}

图中显示的是网页的一个片段,整个网页都有背景图像。图像重复显示,以填充整个屏幕:

文字 “文字 “你好,世界!",背景为反复出现的柔和蓝色,水花四溅,形成环形波纹效果”。

注: 使用 background-image 属性时,如果背景图片小于指定元素的容器(本例中为 <body>元素),则默认情况下背景图片会重复显示。您可以使用各种 CSS 属性来控制背景图片的位置并调整其缩放比例:

  • background-position 指定背景图像的起始位置(例如,centertop left50% 50%)。
  • background-size定义背景图片的大小,允许的值包括 covercontain 或特定尺寸(如 100px 200px)。
  • background-repeat 决定背景图像是否重复(例如,repeatno-repeatrepeat-xrepeat-y)。

这些属性有助于确保背景图片在不同屏幕尺寸和布局下正确显示。

在 HTML 元素中添加背景图像

让我们考虑一下为单独的 HTML 元素(例如 h1 元素)添加背景图片的情况。为防止背景图片重复,我们指定了 background-repeat 属性。

 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}

图中显示的是网页的一个片段–带有<h1>元素背景图片的 HTML 文件:

文字 “文字 “祝你有美好的一天!",背景为柔和的蓝色,水花四溅,形成环形波纹效果”。

使用内联 CSS 添加背景图片

下面展示了如何使用内联 CSS(style属性和<body>元素内的background-image CSS 属性)为<body>元素添加背景图片:

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}

总结与建议

  1. 使用 <img> 标签添加图片或通过 CSS 添加背景图片,可以在视觉上和结构上增强网页内容。根据图片是装饰性的还是对内容至关重要来选择适当的方式。
  2. HTMLDocument 类为动态编辑 HTML 内容提供了灵活性。在修改所需元素(headbodyp 等)(例如添加 CSS 属性)之前,请务必检查它们是否存在。
  3. 使用内部 CSS(<style> 元素)是一种结构化的背景图像设置方法,可使 HTML 更简洁,样式更集中。内联 CSS(style属性)是简单情况下的另一种选择。
  4. 使用 CSS 属性,如 background-sizebackground-repeatbackground-position,确保图像能很好地适应不同的屏幕尺寸。

另见

在 HTML 中添加图像 – 从基本语法到高级技巧 这篇文章中,您将了解添加图像的不同方法,包括使用 <img> 标记、CSS 背景图像、JavaScript 和 Base64 编码。

文章 编辑 HTML 文档为您提供了有关如何读取或修改文档对象模型(DOM)的基本信息。您将了解如何创建 HTML 元素,以及如何使用 Aspose.HTML for .NET 对其进行操作。

Aspose.HTML 提供免费的 HTML 网络应用程序,是转换器、合并器、搜索引擎优化工具、HTML 代码生成器、URL 工具等的在线集合。这些应用程序可在任何装有网络浏览器的操作系统上运行,无需安装任何其他软件。它是一种快速、简便的方法,能有效解决与 HTML 相关的任务。

文本 “HTML 网络应用程序”

Close
Loading

Analyzing your prompt, please hold on...

An error occurred while retrieving the results. Please refresh the page and try again.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.