Bahaa Hany
Bahaa Hany

Reputation: 754

Load image from project folder in a html format to show in webcontrol

I have a windows application for a book. I show the chapter text in a webcontrol, because its in html format. In the chapter text there are some images which I added to a folder called Images. How can I load the specified image in a html tag?

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

I tried to add the images as resources but then I can not add them in the html code above. Please advice.

Upvotes: 1

Views: 2971

Answers (1)

keenthinker
keenthinker

Reputation: 7830

You need to specify the full path to the image. If the images are stored locally, you are allowed to give a normal windows path:

enter image description here

One possible solution in your case would be to put the Images directory in your application folder and access it using the Application.StartupPath property, something like this:

// 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);

You have a couple of options to deliver the images with the executable:

  • create an installer package that handles the dependies for you (e.g. MSI Setup package or ClickOnce)
  • deliver an archive (ZIP containing the EXE and the images folder with the images)
  • embed the images into the EXE, when the application is started, store them in a temp directory and retrieve them from there, when the application exits, delete the images from the temp directory
  • embed the images into the EXE and then use them to embed them directly into to HTML using the URI scheme

A solution for the last option could look like this:

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);

The output is same as the above image. This way you will not need the images directory anymore (or a temp one).

Upvotes: 2

Related Questions