1

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

chapterText += "<div align=center><img [email protected]'Images\\" + imageName + ".jpg' width='350' vspace='5'></div>"; 

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

回答

2

您需要指定图像的完整路径。如果图像存储在本地,你被允许提供一个正常的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的)
  • 递送归档(含有ZIP的EXE并且图像与图像文件夹)
  • 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); 

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

+0

非常感谢感谢,它的工作原理,但只有当我复制bin \ debug \ Images中的Images文件夹。我现在关心的是,当我将该项目定为可执行文件book.exe – 2014-09-21 17:52:15

+0

时,它的工作原理是一样的,答案很有帮助。我已经延长了我的答案。 – pasty 2014-09-21 18:16:55

相关问题