I have images saved in SQL server database as a binary data. Now I want to show these images in the Gridview. But there web control which directly read the data from the database. Web image control requires ImageUrl
property so can not use this as my images are in databases. However i can store the images in a folder but i want some different way which directly read image data from the database and show in a grid.
Asked
Active
Viewed 6,667 times
0

mauris
- 42,982
- 15
- 99
- 131

Rajaram Shelar
- 7,537
- 24
- 66
- 107
-
Have you done a search of existing answers in SO? – IrishChieftain Nov 17 '12 at 16:42
-
Yes, i did but cant find appropriate – Rajaram Shelar Nov 17 '12 at 16:55
-
http://stackoverflow.com/search?q=asp.net+images+database+httphandler – IrishChieftain Nov 17 '12 at 18:30
2 Answers
2
using generic handler you can convert binary data into image and display it
Code:
Set image control url as
Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;
where ShowImage.ashx is a generic handler file.
using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Int32 empno;
if (context.Request.QueryString["id"] != null)
empno = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = ShowEmpImage(empno);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
//context.Response.BinaryWrite(buffer);
}
public Stream ShowEmpImage(int empno)
{
string conn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = "SELECT* FROM table WHERE empid = @ID";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", empno);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
}

Martijn Pieters
- 1,048,767
- 296
- 4,058
- 3,343

Satinder singh
- 10,100
- 16
- 60
- 102
-
-
@eraj: yes this works in my case. well jst try once and let me knw if u find any issues ? – Satinder singh Nov 19 '12 at 17:34
0
the blog may give you some help http://hi.baidu.com/pxvddcbpbrbmqxq/item/3de72787e9e1c6eae496e098

Bohan
- 65
- 1
- 6