Retrieve Image from database

display an Image from PostGreSQL database into Image control using c#

Page 1 of 1

2 Replies - 12495 Views - Last Post: 18 December 2008 - 10:10 PM Rate Topic: -----

#1 chikku07  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 2
  • Joined: 16-December 08

Retrieve Image from database

Post icon  Posted 16 December 2008 - 06:24 AM

Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
	<title>Untitled Page</title>
	<script src="file:///C:/Documents%20and%20Settings/nagasridhar/Desktop/
		Inserting%20Images%20into%20Database%20and%20Display%20it%20in%20GridView%20
		through%20ShowImage_ashx%20-%20Storing%20Images%20in%20SQL%20Server%20DB,
		%20Store%20and%20Display%20Image%20Dynamically%20from%20Database_files/show_ads.js"
		type="text/javascript"> </script>
</head>
<body>
	<form id="form1" runat="server">
	<div>
	<fieldset>
<legend>Upload image to database</legend>
<table>
<tr>
<td style="width: 464px">
File Name:<asp:TextBox ID="txtFileName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 464px">
<input id="File1" runat="server" type="file" /></td>
</tr>
<tr>
<td style="width: 464px; height: 9px;">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
<asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" Width="103px" /><br />
</td>
</tr>

</table>
		
		
		
		<asp:Label ID="Label1" runat="server" Text="Enter Image Name" Width="114px"></asp:Label>
		<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
		
		
		<br/>
	   
<table>
<tr>
<td style="width: 464px; height: 26px;">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
<asp:Button ID="Button2" runat="server" Text="show Image" onclick="Button2_Click" /></td>
</tr>

</table>
</fieldset>

	</div>
		<div>
		&nbsp;
		<asp:GridView ID="GridView1" runat="server" Height="1px" Width="145px">
			<Columns>
				<asp:TemplateField>
					<ItemTemplate>
						<asp:Image ID="Image2" runat="server" Height="49px" ImageUrl='<%# imageURL(DataBinder.Eval(Container.DataItem,"id").ToString()) %>' Width="38px" />
						<asp:Label ID="Label2" runat="server" Height="52px" Text='<%# Server.HtmlEncode(DataBinder.Eval(Container, "DataItem.id").ToString())%>' Width="43px"></asp:Label>
					</ItemTemplate>
				</asp:TemplateField>
				
			</Columns>
		</asp:GridView>
		</div>
	</form>
</body>
</html>



Default5.aspx.cs
using System;
using System.Data;
using Npgsql;
using System.IO;
using System.Configuration;
using System.Collections;
using System.ComponentModel;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;


public partial class Default5 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        FileInfo imageInfo = new FileInfo(File1.Value.Trim());

        if (!imageInfo.Exists)
            this.RegisterClientScriptBlock("alertMsg", "<script>alert('please select one image file.');</script>");
        else
        {
            switch (imageInfo.Extension.ToUpper())
            {
                case ".JPG": this.UpLoadImageFile(imageInfo); break;
                case ".GIF": this.UpLoadImageFile(imageInfo); break;
                case ".BMP": this.UpLoadImageFile(imageInfo); break;
                default: this.RegisterClientScriptBlock("alertMsg", "<script>alert('file type error.');</script>"); break;
            }
        }
    }

    private void UpLoadImageFile(FileInfo info)
    {
        NpgsqlConnection objConn = null;
        NpgsqlCommand objCom = null;
        
        
        
        try
        {
            byte[] content = new byte[info.Length];
            FileStream imagestream = info.OpenRead();
            imagestream.Read(content, 0, content.Length);
            imagestream.Close();

            string DefCon = "server=localhost;database=sln_user;uid=postgres;pwd=skysky1";
            objConn = new NpgsqlConnection(DefCon);
            
            objCom = new NpgsqlCommand("insert into picture " + " (id, pic) values (:id, :pic)", objConn);

            NpgsqlParameter categorynameParameter = new NpgsqlParameter("@id", DbType.String);
            if (this.txtFileName.Text.Trim().Equals(""))
                categorynameParameter.Value = "Default";
            else
                categorynameParameter.Value = this.txtFileName.Text.Trim();
            objCom.Parameters.Add(categorynameParameter);

            NpgsqlParameter pictureParameter = new NpgsqlParameter("@pic", DbType.Binary);
            pictureParameter.Value = content;
            objCom.Parameters.Add(pictureParameter);

            objConn.Open();
            objCom.ExecuteNonQuery();
            this.RegisterClientScriptBlock("alertMsg", "<script>alert('Image uploaded successfully.');</script>");
            //Response.Write("Image Uploaded Successfully");
            objConn.Close();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            objConn.Close();
        }
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
             
        try
        {
            
            GridView1.DataSource = FetchAllImagesInfo();
            GridView1.DataBind();
        }
            
        finally
        {
            //connection.Close();
            //stream.Close();
        }
    }
        public DataTable FetchAllImagesInfo()
        {
            string sql = "select * from picture where id = '" + TextBox1.Text + "'";
        NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, "server=localhost;database=sln_user;uid=postgres;pwd=skysky1"); 
        DataTable dt = new DataTable(); 
        da.Fill(dt); 
        return dt; 
        }
    public string imageURL(string id)
    {
        return ("~/ShowImage.ashx?test=" + id);
    }
    }



[/b]ShowImage.ashx
<%@ WebHandler Language="C#" Class="ShowImage" %>

using System;
using System.Web;
using System.IO;
using Npgsql;
using System.Configuration;
using System.Collections;
//using System.Web;
using System.Data.SqlClient;
using System.ComponentModel;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;


public class ShowImage : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        NpgsqlConnection myConnection = new NpgsqlConnection("server=localhost;database=sln_user;uid=postgres;pwd=skysky1");
        myConnection.Open();
        string sql = "Select pic from picture where id=@ImageId";
        NpgsqlCommand cmd = new NpgsqlCommand(sql, myConnection);
        cmd.Parameters.Add("@ImageId", NpgsqlTypes.NpgsqlDbType.Integer).Value = context.Request.QueryString["test"];
        cmd.Prepare();
        NpgsqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        context.Response.ContentType = dr["id"].ToString();
        context.Response.BinaryWrite((byte[])(dr["pic"]));
    }

 public bool IsReusable {
        get {
            return false;
        }
    }
}



Mod Edit: Please use code tags when posting your code. Code tags are used like so => :code:

Thanks,
PsychoCoder :)

Is This A Good Question/Topic? 1

Replies To: Retrieve Image from database

#2 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1641
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: Retrieve Image from database

Posted 16 December 2008 - 04:14 PM

Are you receiving any errors? Does this code not work that way you intended it? When asking for help there are a couple items that are vital in order for someone to properly help you:

  • Post the code you're having problems with (DONE)
  • Post the exact error you're receiving, if you are receiving one
  • If no error explain what the code is doing versus what you want it to do
  • Post your question in the body of your post, not the description field


Lastly, this is ASP.NET code so this is being moved to the ASP.NET forum :)
Was This Post Helpful? 0
  • +
  • -

#3 chikku07  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 2
  • Joined: 16-December 08

Re: Retrieve Image from database

Posted 18 December 2008 - 10:10 PM

View PostPsychoCoder, on 16 Dec, 2008 - 03:14 PM, said:

Are you receiving any errors? Does this code not work that way you intended it? When asking for help there are a couple items that are vital in order for someone to properly help you:
  • Post the code you're having problems with (DONE)
  • Post the exact error you're receiving, if you are receiving one
  • If no error explain what the code is doing versus what you want it to do
  • Post your question in the body of your post, not the description field
Lastly, this is ASP.NET code so this is being moved to the ASP.NET forum :)


Sorry for the inconvinence since am new to this community i was not knowing the procedure. Now am aware of it and the this error wont happen again.
My problem in the code is am not able to retrieve an image from the database inside an image control. when i run the code the progress bar get struck in the middle and in the status bar it will display downloading picture. but nothing will be displayed.
Plz help me in this regard.
Thanks in advance.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1