Click here to Skip to main content
15,885,216 members
Articles / Web Development / ASP.NET

Display/Store and Retrieve Image Data from Database to Gridview, and also on Mouse Over

Rate me:
Please Sign up or sign in to vote.
4.44/5 (21 votes)
15 Oct 2011CPOL4 min read 127.9K   9.9K   50  
How to Display/Store and Retrieve Image Data from Database to Gridview, and also on mouse over
<%@ WebHandler Language="C#" Class="ShowPosterImg" %>
using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class ShowPosterImg : 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";
        System.IO.Stream strm = ShowEmpImage(empno);
        byte[] buffer = new byte[32768];
        int byteSeq = strm.Read(buffer, 0, 32768);   //4094

        while (byteSeq > 0)
        {
            context.Response.OutputStream.Write(buffer, 0, byteSeq);
            byteSeq = strm.Read(buffer, 0, 32768);
        }  
    }

    private System.IO.Stream ShowEmpImage(int empno)
    {
        string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(conn);
        string sql = "SELECT BytesPoster FROM User WHERE empid = @ID";
        System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, connection);
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", empno);
        connection.Open();
        object img = cmd.ExecuteScalar();
        try
        {
            return new System.IO.MemoryStream((byte[])img);
        }
        catch
        {
            return null;
        }
        finally
        {
            connection.Close();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
 

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Software Developer (Senior) ***
Philippines Philippines
MCTS - Microsoft Certified Technology Specialist.
An Accountant.
Had been developed Payroll Accounting System Application
Live in: Quezon City, Metro Manila Philippines
Could reached at email address: ag_mojedo@live.com

Comments and Discussions