1

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

2 Answers 2

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>");                  
Sign up to request clarification or add additional context in comments.

2 Comments

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)?
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?
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.