c# - 以 html 格式从项目文件夹加载图像以在 webcontrol 中显示

标签 c# visual-studio-2012 webbrowser-control windows-applications

我有一本书的 Windows 应用程序。我在 web 控件中显示章节文本,因为它是 html 格式。在章节文本中有一些图像,我将它们添加到名为 Images 的文件夹中。如何在 html 标签中加载指定的图像?

chapterText += "<div align=center><img src=@'Images\\" + imageName + ".jpg' width='350' vspace='5'></div>";

我尝试将图像添加为资源,但我无法将它们添加到上面的 html 代码中。 请指教。

最佳答案

您需要指定图像的完整路径。如果图像存储在本地,您可以提供一个正常的 windows 路径:

enter image description here

在您的情况下,一个可能的解决方案是将 Images 目录放在您的应用程序文件夹中,并使用 Application.StartupPath property 访问它。 ,像这样:

// fetch directory where images reside, e.g.: c:\temp\app\images\
var imagePath = Path.Combine(Application.StartupPath, @"Images");
// create image path, e.g.: c:\temp\app\images\one.jpg
var imageFile = Path.Combine(imagePath, String.Format("{0}.jpg", imageName));
// use it
chapterText += String.Format("<div align=center><img src='{0}' width='350' vspace='5'></div>", imageFile);

您有几个选项可以使用可执行文件传送图像:

  • 创建一个安装程序包来为您处理依赖项(例如 MSI 安装包或 ClickOnce)
  • 提供一个存档(包含 EXE 的 ZIP 和带有图像的图像文件夹)
  • embed the images into the EXE ,当应用程序启动时,将它们存储在临时目录中并从那里检索它们,当应用程序退出时,从临时目录中删除图像
  • 将图像嵌入到 EXE 中,然后使用 URI scheme 将它们直接嵌入到 HTML 中

最后一个选项的解决方案可能如下所示:

var image = @"d:\temp\image.jpg";
// use MemoryStream to load the image from the embedded ressource
var imageAsBase64 = Convert.ToBase64String(File.ReadAllBytes(image));
var webBrowser = new WebBrowser();
// embed the image directly into the html code, no need to load it from the file system
webBrowser.DocumentText = String.Format("<html><body><img src='data:image/jpg;base64,{0}' /></body></html>", imageAsBase64);

输出与上图相同。这样您将不再需要图像目录(或临时目录)。

关于c# - 以 html 格式从项目文件夹加载图像以在 webcontrol 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25960465/

相关文章:

c# - Mysql + Visual Studio 2012 "Failed to find or load the registered .Net Framework Data Provider"

VB.Net Web 浏览器控件 - 如何处理弹出窗口?

c# webbrowser 控制打印

c# - 从类继承

c# - 使用 C# 导出到 OneNote

c# - 在 webBrowser 控件中禁用 Ctrl+P

c++ - 会用VS2012进行boost编译吗?

tfs - TF31002 : Unable to Connect to this Team Foundation server

c# - 如何从托管 Web 浏览器控件的应用程序调用 Web 浏览器控件查看的页面中的 JavaScript 函数?

c# - ServiceStack Client Put请求和查询参数