locked
Image display from database when stored as byte array

    Pregunta

  • Hai  friends ,

    I have a problem in displaying byte array from database (sql) to image in a web page ..

    please help me in this problem

    This is my code from  handler page

    public void ProcessRequest(HttpContext context)
        {
            System.Data.SqlClient.SqlDataReader rdr = null;
            System.Data.SqlClient.SqlConnection conn = null;
            System.Data.SqlClient.SqlCommand selcmd = null;
            try
            {
                conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MySampleDBConnectionString"].ConnectionString);
                if (context.Request.QueryString["LoginName"] != null)
                {
                    selcmd = new System.Data.SqlClient.SqlCommand("select Photo from PersonalDetails where LoginName =" + context.Request.QueryString["LoginName"], conn);
                }
                else
                {
                    return;
                }
                conn.Open();
                rdr = selcmd.ExecuteReader();
                while (rdr.Read())
                {
                    context.Response.ContentType = "image/jpg";
                    context.Response.BinaryWrite((byte[])rdr["LoginName"]);
                }
                if (rdr != null)
                    rdr.Close();
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    This is image ,Url

    imgPhoto.ImageUrl = ("~/ImageHandler.ashx?LoginName =  " + Session[LoginName]);

    This is image tag

    //<asp:Image ID="imgPhoto" runat="server" Width ="150px" Height ="150px" />

    Here in my code i have a login name corresponding to that login name i store my photo

    Thanks in advance ...

    waiting for your valuable adwise

    Thanks and regards

    Leenu


    Leenu Thomas

    lunes, 05 de marzo de 2012 8:46

Respuestas

  • Hi Leenu,

    Please try this code: 

        Public Function Load_Pic_Sql(ByVal id As Integer) As Image
            'for sql server
            Dim conn As SqlConnection = New SqlConnection()
            conn.ConnectionString = "Data Source=datasource;Initial Catalog=LoadTest;Persist Security Info=True;User ID=test;Password=123"
    
            'for SQL 
            Dim sql As String = "select img from picture where id = " & id
            Dim command1 As SqlCommand = New SqlCommand(sql, conn)
            conn.Open()
            Dim reader As SqlDataReader = command1.ExecuteReader
            reader.Read()
            Dim bitPic() As Byte = CType(reader.GetValue(0), Byte())
    
            conn.Close()
            Dim mStream As MemoryStream = New MemoryStream(bitPic)
            Dim img As Image = Image.FromStream(mStream)
    
            Return img
    
        End Function
    
        Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
            'Dim cn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & _
            '"Data Source=d:\db\Database11.accdb")
            Dim cn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & _
                    "Data Source=d:\db\Population Data.accdb")
            cn.Open()
    
            'Dim Command As New OleDbCommand("SELECT pic from pic where id = 1", cn)
            Dim Command As New OleDbCommand("SELECT flag from [Population Data] where id = 5", cn)
            Dim Reader As OleDbDataReader = Command.ExecuteReader()
            Dim picture As Image = Nothing
    
            While Reader.Read
                Dim pictureData() As Byte = CType(Reader.GetValue(0), Byte())
                Using stream As New IO.MemoryStream()
                    picture = Image.FromStream(stream)
                End Using
                Dim img As Image = My.Resources.msdn2008
            End While
            Me.PictureBox2.Image = picture
            cn.Close()
        End Sub

    I hope this will be helpful.

    Best regards,


    Mike Feng
    MSDN Community Support | Feedback to us
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    martes, 06 de marzo de 2012 15:39
  • hi friends,

    My page is ashx and i can't use session in it..

    is there any way to session in it?

    please help ...

    Thanks in advance


    Leenu Thomas

    Hi Leenu,

    Please take a look at this discussion: http://www.codeproject.com/Questions/184412/How-to-access-session-in-ashx-file

    yes you can access the session in your ashx file. For that you need to implement IRequiresSessionState interface in your handler class.
    Then you can access session as context.Session. Here context is the object of class HttpContext, which is passed as a parameter in ProcessRequest method. 

    I hope this will be helpful.

    Best regards,


    Mike Feng
    MSDN Community Support | Feedback to us
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    miércoles, 07 de marzo de 2012 6:39

Todas las respuestas


  • Leenu Thomas

    lunes, 05 de marzo de 2012 6:59
  • Hii Leenu

    Move ProcessRequest() codes into Page_Load(object sender, EventArgs e) of ImageHandler.apx.. try again...


    Nidhinraj

    lunes, 05 de marzo de 2012 9:27
  • // ImageHandler.aspx

    protected void Page_Load(object sender, EventArgs e)
            {
                try
                {
                    string sSsnImage = string.Empty;       // String variable represents image from session
                    System.Drawing.Image imgImage = null;  // Image variable represents image
                    Bitmap bmpImage = null;                // Bitmap object represents bitmap image

                    // Check null status of query string
                    if (Request.QueryString["imgSsnKey"] == null)
                    {
                        return;
                    }

                    sSsnImage = Request.QueryString["imgSsnKey"];
                    imgImage = (System.Drawing.Image)Session[sSsnImage];
                    bmpImage = new Bitmap(imgImage);
                    Response.ContentType = "image/jpeg";
                    bmpImage.Save(Response.OutputStream, ImageFormat.Jpeg);
                    bmpImage.Dispose();
                }
                catch (Exception)
                {
                    Debug.Assert(false);
                }
            }

    Image Url

    ImageUrl="~/ImageHandler.aspx?imgSsnKey=ssnUserImage"

    Setting Image to session from UserPage

     Session["ssnUserImage"] = imgUserImage;

    try this one..


    Nidhinraj

    lunes, 05 de marzo de 2012 10:02
  • hi friends,

    My page is ashx and i can't use session in it..

    is there any way to session in it?

    please help ...

    Thanks in advance


    Leenu Thomas

    lunes, 05 de marzo de 2012 15:27
  • Hi Leenu,

    Please try this code: 

        Public Function Load_Pic_Sql(ByVal id As Integer) As Image
            'for sql server
            Dim conn As SqlConnection = New SqlConnection()
            conn.ConnectionString = "Data Source=datasource;Initial Catalog=LoadTest;Persist Security Info=True;User ID=test;Password=123"
    
            'for SQL 
            Dim sql As String = "select img from picture where id = " & id
            Dim command1 As SqlCommand = New SqlCommand(sql, conn)
            conn.Open()
            Dim reader As SqlDataReader = command1.ExecuteReader
            reader.Read()
            Dim bitPic() As Byte = CType(reader.GetValue(0), Byte())
    
            conn.Close()
            Dim mStream As MemoryStream = New MemoryStream(bitPic)
            Dim img As Image = Image.FromStream(mStream)
    
            Return img
    
        End Function
    
        Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
            'Dim cn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & _
            '"Data Source=d:\db\Database11.accdb")
            Dim cn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & _
                    "Data Source=d:\db\Population Data.accdb")
            cn.Open()
    
            'Dim Command As New OleDbCommand("SELECT pic from pic where id = 1", cn)
            Dim Command As New OleDbCommand("SELECT flag from [Population Data] where id = 5", cn)
            Dim Reader As OleDbDataReader = Command.ExecuteReader()
            Dim picture As Image = Nothing
    
            While Reader.Read
                Dim pictureData() As Byte = CType(Reader.GetValue(0), Byte())
                Using stream As New IO.MemoryStream()
                    picture = Image.FromStream(stream)
                End Using
                Dim img As Image = My.Resources.msdn2008
            End While
            Me.PictureBox2.Image = picture
            cn.Close()
        End Sub

    I hope this will be helpful.

    Best regards,


    Mike Feng
    MSDN Community Support | Feedback to us
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    martes, 06 de marzo de 2012 15:39
  • hi friends,

    My page is ashx and i can't use session in it..

    is there any way to session in it?

    please help ...

    Thanks in advance


    Leenu Thomas

    Hi Leenu,

    Please take a look at this discussion: http://www.codeproject.com/Questions/184412/How-to-access-session-in-ashx-file

    yes you can access the session in your ashx file. For that you need to implement IRequiresSessionState interface in your handler class.
    Then you can access session as context.Session. Here context is the object of class HttpContext, which is passed as a parameter in ProcessRequest method. 

    I hope this will be helpful.

    Best regards,


    Mike Feng
    MSDN Community Support | Feedback to us
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    miércoles, 07 de marzo de 2012 6:39