0

I want to generate and output an html file with images using C# winforms. I have a few images in the Resources folder, but I'm not able to output them to html.

Could anyone suggest how to access and output images present in Resources to an html file?

My code:

using System;
using System.Windows.Forms;
using System.IO;
namespace winformToHtml
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_report_Click(object sender, EventArgs e)
        {
            StreamWriter sWrite = new StreamWriter("C:\\report.html");
            sWrite.WriteLine("<html>");
            sWrite.WriteLine("<body>");
            sWrite.WriteLine("<p> <img src= 'Resources/image.png' height='10%' width='5%' > </p>");                  
            sWrite.WriteLine("<body>");
            sWrite.WriteLine("<html>");
            sWrite.Close();
        }
    }
}
pNre
  • 5,376
  • 2
  • 22
  • 27
harishli2020
  • 305
  • 6
  • 19

2 Answers2

2

You can use IMG base 64 syntax to render your picture :

   public static String Base64Encoded(Image image) 
   {
        using (MemoryStream m = new MemoryStream())
            {
                image.Save(m, ImageFormat.Jpeg);
                byte[] imageBytes = m.ToArray();

                // Convert byte[] to Base64 String
                string base64String = Convert.ToBase64String(imageBytes);
                return base64String;
            }    
    }

Then :

 sWrite.WriteLine("<p><img src='data:image/jpeg;base64," + Base64Encoded(Resource.Image) + "' height='10%' width='5%' > </p>");                  
Perfect28
  • 11,089
  • 3
  • 25
  • 45
  • 1
    I'm getting an error at the line image.Save(image, ImageFormat.Jpeg);.I think it should be image.Save(m, ImageFormat.Jpeg); and Base64Encoded(Resource.Image) be Base64Encoded(Resources.Image)? – harishli2020 Jan 13 '15 at 15:49
  • When I'm exporting the image to html some part of the image from bottom is missing. Could you please suggest me how fix this problem? – harishli2020 Jan 14 '15 at 07:21
0

Your question is missing parts from the story. I'm assuming you have embedded resources in your application and you write an html file that should work from outside your application. The html file references images that are embedded in your executable.

You need to extract those resources to the directory where you write the html file.

If they aren't embedded, you can just use File.Copy().

If you want the html file to be self-contained (i.e. no external references), you can also write the images in the html using base64, for that see @Haga's answer.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272