H.Vin H.Vin - 3 years ago 238
HTML Question

How to embed a C# Image in a web response

I have created something like this: https://www.codeproject.com/Tips/485182/Create-a-local-server-in-Csharp

But the tutorial only shows how to send a string. But when I try to modify the code by adding an

img src
, it won't show up. This is what I have done so far:

private void sendData(int total, DataGridView dgv, Image v)
Thread t = new Thread(() => ResponseThread(total, dgv,v));

private void ResponseThread(int t, DataGridView dgv, Image u)
String table="";
HttpListenerContext context = _httpListener.GetContext();
for (int i = 0; i < t; i++)
table += "<tr><td>" + dgv.Rows[i].Cells[0].Value.ToString() + "</td><td>" + dgv.Rows[i].Cells[1].Value.ToString() + "</td><td>" +
dgv.Rows[i].Cells[2].Value.ToString() + "</td><td>" + dgv.Rows[i].Cells[3].Value.ToString() + "</td><td>" + dgv.Rows[i].Cells[4].Value.ToString() +
"</td><td>" + dgv.Rows[i].Cells[5].Value.ToString() + "</td></tr>";

byte[] _responseArray = Encoding.UTF8.GetBytes(
"<html>" +
"<head>" +
"<title>Hello</title>" +
"</head>" +
"<body>" +
"<h1>Total: " + t +
"<table style=\"width:100%\"> <tr><b><th>No</th><th>Centroid X</th><th>Centroid Y</th><th>Orientation</th><th>Area</th><th>Area (mm)</th></b></tr>"+
"<img src="+u+"></img>"+
"<p><i>Last Update: " + DateTime.Now.ToShortDateString() + " "+DateTime.Now.ToLongTimeString()+
"</i></p>" +
context.Response.OutputStream.Write(_responseArray, 0, _responseArray.Length);
context.Response.KeepAlive = true;

Answer Source

When you add u (Image variable) to a string, .NET framework will call u.ToString() and add the output to the string, so the result string will be <img src="Image"</img>

If you need to make it correct:

  1. Either pass the URL of the image, if its on a common place.

  2. Base64 encode the image and keep it inline (within the html). Example:

<img alt="Embedded Image" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download