Click here to Skip to main content
15,918,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear All,

I have a table named images in SQL Server 2008 and it contains two columns imageid and image.

Now I am able to insert images in to image column using file uploader controller and image which i have converted to binary form for storing.

Now I want to display the images in a image box correspondence with the image id.

I used TextBox for receiving the id and a button to execute the command for displaying. I am using asp.net as front end.
C#
public void ShowImage()
{
    SqlConnection con = new SqlConnection();
    con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["anu"].ToString();
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "Select ID,Image from Images where ID=" + txtid.Text;
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.Connection = con;   
    
    con.Open();
    SqlDataReader dreader = cmd.ExecuteReader();
    dreader.Read();
    Context.Response.BinaryWrite((byte[])dreader["image"]);
    dreader.Close();
    con.Close();
}  

This code is working fine, but it displaying the picture in a different page but I need to display the picture in the image box which I have added.

If anyone who know the answer, please help me.


Regards,
Rajeev K
Posted
v2

1 solution

<img src="img.ashx?id=999"></img>

img.ashx:
C#
public class img : IHttpHandler
{
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/png";
        Image i = null;

        //Load image here

        var ms = new MemoryStream();

        i.Save(ms, ImageFormat.Png);
        var msToArray = ms.ToArray();
        context.Response.BinaryWrite(msToArray);

       // 1 year cache
       // TimeSpan refresh = new TimeSpan(365, 0, 0, 15, 0);
       // context.Response.Cache.SetExpires(DateTime.Now.Add(refresh));
       // context.Response.Cache.SetMaxAge(refresh);
       // context.Response.Cache.SetCacheability(HttpCacheability.Public);
       // context.Response.CacheControl = HttpCacheability.Public.ToString();
       // context.Response.Cache.SetValidUntilExpires(true);
    }
}
 
Share this answer
 
v2
Comments
Rajeev Krishna 2-Aug-13 5:12am    
ghgh
Rajeev Krishna 2-Aug-13 5:14am    
Hi Tadit,

Thanks for answering my question.

could you please explain how processrequest method can receive the ID( id column in database) from text box,then only it could possible to take diffrent images from database based on the id.Also explain how to load the same picture to imange controller.


Regards,
Rajeev K.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900