我有一本书的 Windows 应用程序。我在 web 控件中显示章节文本,因为它是 html 格式。在章节文本中有一些图像,我将它们添加到名为 Images 的文件夹中。如何在 html 标签中加载指定的图像?
chapterText += "<div align=center><img src=@'Images\\" + imageName + ".jpg' width='350' vspace='5'></div>";
我尝试将图像添加为资源,但我无法将它们添加到上面的 html 代码中。 请指教。
最佳答案
您需要指定图像的完整路径。如果图像存储在本地,您可以提供一个正常的 windows 路径:
在您的情况下,一个可能的解决方案是将 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/