Save image from System.Web.UI.WebControls.Image into database


The objective of this post is to know:-

  1. How do I save an image displayed using System.Web.UI.WebControls.Image control into the database.
  2. How do I retrieve the image from database and display it again onto the System.Web.UI.WebControls.Image control.
The image will be saved into the table as datatype: image

The project that I am doing:-

  1. A webform (web-application) project.
  2. I read a smartcard that contains information of a user. The smartcard contains the photo of the user, name, address, etc.
  3. The image retrieved from the smartcard is saved into the current project folder. Using Server.MapPath("MyKad.bmp");
  4. All the information of the user are displayed into its respective textboxes.
  5. The image is display by >> imgPicFace.ImageUrl = "~/MyKad.bmp";

The code below shows what I have attempted:-


1    #region SaveInfo
2        bool SaveInfo()
3        {
4            string connectionString = "Data Source=.\\SQLExpress;Initial Catalog=RnD; Integrated Security=True";
6            string commandString = "SELECT * FROM tbl_MyKad2";
7            try
8            {
9                SqlDataAdapter DataAdapter = new SqlDataAdapter(commandString, connectionString);
10               DataSet dataSet = new DataSet();
11               DataAdapter.Fill(dataSet);
12               DataTable dataTable = dataSet.Tables[0];
13               DataRow newRow = dataTable.NewRow();
15               if (txtICNo.Text != "")
16               {
17                   #region Alpha-numeric
18                   newRow["IC_No"] = txtICNo.Text;
19                   newRow["OldIC_No"] = txtOldICNo.Text;
20                   newRow["Name"] = txtName.Text;
21                   newRow["Address1"] = txtAddress1.Text;
22                   newRow["Address2"] = txtAddress2.Text;
23                   newRow["Address3"] = txtAddress3.Text;
24                   newRow["Postcode"] = txtPostcode.Text;
25                   newRow["City"] = txtCity.Text;
26                   newRow["State"] = txtState.Text;
27                   newRow["RecordDate"] = DateTime.Now.ToShortDateString();
28                   #endregion
30                   #region Picture
31                   if (imgPicFace.ImageUrl != null)
32                   {                    
34                       MemoryStream stream = new MemoryStream();
35                       imgPicFace.Image.Save(stream, ImageFormat.Jpeg);
36                       stream.Position = 0;
37                       byte[] data = new byte[stream.Length];
38                       stream.Read(data, 0, Convert.ToInt32(stream.Length));
39                       newRow["Photo"] = data;
40                   }
41                   #endregion
45                   dataTable.Rows.Add(newRow);
46                   SqlCommandBuilder oleCom = new SqlCommandBuilder(DataAdapter);
48                   DataAdapter.Update(dataSet);
50                   dataSet.AcceptChanges();
51                   return true;
52               }
53               else if (txtICNo.Text == "")
54               {
55                   return false;
56               }
57               return false;
59           }
60           catch (Exception ex)
61           {
62               Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "script", common.mypopup("" + ex));
63               return false;
64           }
65       }
66       #endregion

Below is the code for retrieving the Photo:


1    #region RetrieveInfo
2        public bool RetrieveInfo(string icno)
3        {
4            string connectionString = "Data Source=.\\SQLExpress;Initial Catalog=RnD; Integrated Security=True";
6            string commandString = "SELECT * FROM tbl_MyKad2 WHERE IC_No = '" + icno + "'";
8            try
9            {
10               SqlDataAdapter DataAdapter = new SqlDataAdapter(commandString, connectionString);
11               DataSet dataSet = new DataSet();
12               DataAdapter.Fill(dataSet);
13               DataTable dataTable = dataSet.Tables[0];
15               if (dataTable.Rows.Count > 0)
16               {
17                   Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "script", common.mypopup("Data Found!"));
18               }
19               else
20               {
21                   Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "script", common.mypopup("Data Not Found!"));
22               }
24               foreach (DataRow dr in dataTable.Rows)
25               {
27                   #region Alpha-numeric
28                   txtICNo.Text = dr["IC_No"].ToString();
29                   txtOldICNo.Text = dr["OldIC_No"].ToString();
30                   txtName.Text = dr["Name"].ToString();                
31                   txtAddress1.Text = dr["Address1"].ToString();
32                   txtAddress2.Text = dr["Address2"].ToString();
33                   txtAddress3.Text = dr["Address3"].ToString();
34                   txtPostcode.Text = dr["Postcode"].ToString();
35                   txtCity.Text = dr["City"].ToString();
36                   txtState.Text = dr["State"].ToString();                
37                   #endregion
39                   #region Picture
40                   if (!(dr["Photo"] is System.DBNull))			//Getting the Bitmap from the DB
41                   {
42                       byte[] photoByte = null;
43                       int ArraySize;
44                       photoByte = (byte[])dr["Photo"];
45                       ArraySize = photoByte.GetUpperBound(0);
46                       MemoryStream ms = new MemoryStream(ArraySize + 1);
47                       ms.Write(photoByte, 0, ArraySize + 1);
49                       Response.ContentType = "image/jpeg";
50                       Response.OutputStream.Write(photoByte, 0, photoByte.Length);
52                       Response.BinaryWrite(photoByte);
54                       Response.End();
56                       ms.Close();
57                   }
58                   #endregion
60               }
62               return true;
64           }
65           catch (Exception ex)
66           {
67               Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "script", common.mypopup("" + ex));
68               return false;
70           }
71       }
72       #endregion

However there is an error at the SAVE and RETRIEVAL part of the image. This code only works in winform and not webform. From what I have read in the Internet:- (**Correct me if I am wrong**)

  • To save image from System.Web.UI.WebControls.Image, first you need to save the image file physically. I have done so and MyKad.bmp resides in the project folder.
  • And to retrieve the image, you do some sort of conversion into BMP file. Then place the BMP file at the current folder so that you can retrieve it using ImageUrl.

The problem is I do not know how to implement it in coding. Please provide coding example. Thank you in advance.

3/6/2008 5:52:36 AM 93655 articles. 6 followers. Follow

2 Replies

Similar Articles

[PageSpeed] 5

I have successfully SAVE the image from control imgPicFace into the database with this code

1    Bitmap b = new Bitmap(Server.MapPath("MyKad.bmp"));
2    System.Drawing.Image i = (System.Drawing.Image)b;
4    MemoryStream streamP = new MemoryStream();
5    i.Save(streamP, ImageFormat.Jpeg);
6    streamP.Position = 0;
7    byte[] data = new byte[streamP.Length];
8    streamP.Read(data, 0, Convert.ToInt32(streamP.Length));
9    newRow["Photo"] = data;

However I have not found the solution to RETRIEVE the Image from database and place it into System.Web.UI.WebControls.Image >> imgPicFace

Please help and provide me the code. Thank you in advance.

3/6/2008 8:55:35 AM

Hi premierax5,

It seems this is the double thread, please focus on your another thread:

Hope it helps,

Hong Gang


Hong-Gang Chen
Microsoft Online Community Support
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
3/10/2008 11:16:58 AM

Similar Artilces:

Save image from System.Web.UI.WebControls.Image to database
Save image from System.Web.UI.WebControls.Image to databaseI do not know the coding on:1. How to save image from System.Web.UI.WebControls.Image control to the database.2. The code the retrieve the image from the database and display back onto the control.The project that I am doing is in WEBFORM. The project reads a smartcard of the user and display the data inside the smartcard onto control such as textboxes and image control. Then save it into the database. I read the image by:- (with success)mykad.SaveImage(Server.MapPath("MyKad.bmp"));       ...

System.Drawing.Image TO System.Web.UI.WebControls.Image
Is there a way to convert an System.Drawing.Image to an System.Web.UI.WebControls.Image? Im getting the image from an XML file, the binary being in base 64 string. I then convert it back to an array of bytes. My problem is that I can't find a way to create the System.Web.UI.WebControls.Image with a Stream or an array of bytes... I got the Image from Drawing but I can't convert it back to a WebControl Image. I suppose I must write down the file somewhere on the server then return the path but I dont want to leave these temporary images on the drive. Any ideas or suggestion anyone?...

System.Drawing.Image to System.Web.UI.Webcontrols.Image
How do I convert this?DaveHelixpoint LLCHarrisburg Web Developer These two are entirely two different classes meant for different things: System.Drawing.Image represents the binaray/raw form of an image where as System.Web.UI.WebControls.Image is a ASP.NET server-side control used to render an image.Mark replies as answers if they helped you solve the problem.  You should save the image to a physical file in your web application folder and set the ImageUrl property of the Image control to the virtual path. example belowSave image to a physical folder.Once it is saved (suppose you sa...

'Image' is an ambiguous reference between 'System.Web.UI.WebControls.Image' and 'System.Drawing.Image'
In my aspx page, I have the following snippet: <%@ Page Language="C#" %><%@ Import Namespace="System.IO" %><%@ Import Namespace="System.Drawing" %>     public System.Drawing.Image Test()    {      ...    }  I keep getting the 'Image' is an ambiguous reference between 'System.Web.UI.WebControls.Image' and 'System.Drawing.Image' error in my Test function (which returns an Image). How do I fix this? Right which is possible; use the full...

CS0104: 'Image' is an ambiguous reference between 'System.Web.UI.WebControls.Image' and 'System.Drawing.Image'
 CS0104: 'Image' is an ambiguous reference between 'System.Web.UI.WebControls.Image' and 'System.Drawing.Image'   <%@ Page Language="C#" %> <%@ Import Namespace="System.Drawing" %> <%@Import Namespace="System.Drawing.Imaging" %>   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""><script type="text/C#" runat="server"> void Page_Load() {//The @ means "Ignore escape characters!" in the following string. It is a verbatim //literal string - any backslashes (and newlines) in...

convert System.Web.UI.WebControls.Image into System.Drawing.Image
Hi!is there some way using that I can typecast System.Web.UI.WebControls.Image into System.Drawing.Image? I want to convert an image from System.Web.UI.WebControls.Image to System.Drawing.Image. Thanks in advance... VB        Dim img As System.Drawing.Image        img = System.Drawing.Image.FromFile(Server.MapPath(Image1.ImageUrl)) C#        System.Drawing.Image img = null;        img = System.Drawing.Image.FromFile(Server.MapPath(Image1.ImageUrl));  ...

Convert System.Drawing.Image into System.Web.UI.Webcontrols.Image
hi, whenever i retrive image from the database as  bytes array, i can convert bytes array into bitmap but i cannot assign bitmap(System.Drawing.Image)  to image control(System.Web.UI.Webcontrols.Image). it is possibe to convert this. please provide me a solution. by venkatesan T. Hi,       One way is save the Image(System.Drawing.Image) in a path ,and give the saved path to ImageUrl of the ImageButton .For Eg: System.Drawing.Image img = System.Drawing.Image.FromFile(@"c:/inetpub/wwwroot/Forum/Undo.gif"); string filename="c:/inetpub/wwwroo...

Show Image on the System.Web.UI.WebControls.Image
Hi I have image stored as bytes in the SQL Database. I can read this into byte array depending on the user selection. Now I want to show the loaded image (which is in byte array) in the image control on my aspx page. Can somebody help me with this You'll want to set the ImageUrl tag to an ASPX page, and then make that ASPX page retrieve the image and output it to the http output stream. See this article for more info: WallingASP.NET MVPMy blog, Software by RobPlease click "Mark as Answer&...

Converting 'System.Drawing.Image' to 'System.Web.UI.WebControls.Image'
Hello,I have an image stored on disk, that I am manipulating using the Drawing classes, and creating a 300x400 thumbnail from. Then, I want to display this image in an Image control on my webpage. How do I do that?Code:                    //Create the delegate                    System.Drawing.Image.GetThumbnailImageAbort dummyCallBack;           &nbs...

Help to retrieve image from database and display in Web.UI.WebControls.Image
Hi! I am a newbie. I want to retrieve image from database and display it in Web.UI.WebControls.Image.The control name is imgPicFace.And I want when it retrieve from database the control point like this >>>  imgPicFace.ImageUrl = "~/MyKad.bmp"; Please help and provide example code for me. Thank you.SAVE CODE:- 1 Bitmap b = new Bitmap(Server.MapPath("MyKad.bmp")); 2 System.Drawing.Image i = (System.Drawing.Image)b; 3 4 MemoryStream streamP = new MemoryStream(); 5 ...

Dynamicly created System.Web.UI.WebControls is not copied to staticly creadted System.Web.UI.WebControls
Below is dynamicly created Table  System.Web.UI.WebControls.Table Tablex = new Table(); Below is staticly created Table  <asp:Table ID="Table1" runat="server"></asp:Table>   After some operations over Tablex, I want to make Table1 = Tablex. But Table1 did not take effect. I'm sure Tablex contains rows and cells that has data inside them. Table1 = Tablex; //No take effect   Thanks Why can't you just make the changes to Table1.  What is the need for creating a dynamic table and then assigning it to static table. ...

difference between "using System.Web.UI.WebControls" or "System.Web.UI.WebControls.ServerValidateEventArgs"
Hi all, quick question. I'm writing a custom validation method. In the declaration it has: protected void CustomValidator1_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args) Is there any difference between doing that, vs doing: using System.Web.UI.WebControls; protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) Do they do the same thing? Is it any more efficient when processing the request to do it one way or another? Is there a technical term for what i am talking about? Thanks in advance for any explanation ...

System.Drawing.Bitmap vs. System.Web.UI.WebControls.Image
Hi,I am getting a problem with assign a System.Drawing.Bitmap to a System.Web.UI.WebControls.Image  First I want to show my code to draw a graphics in which g is: g = Graphics.FromImage(DrawingBitmap);1 protected void DrawGraphic(object sender, EventArgs e) 2 { 3 g.Clear(Color.WhiteSmoke); 4 5 draw24Hours(g); 6 7 DrawingBitmap.Save(Server.MapPath("sample.jpeg"), System.Drawing.Imaging.ImageFormat.Jpeg); 8 WebControlImage.ImageUrl = Server.MapPath("sample.jpeg"); 9 ...

Upcast System.Web.UI.Control to System.Web.UI.WebControl?
I'm getting a "Specified cast is invalid" error when trying the following: WebControl wc = (WebControl)control; Where "control" is a System.Web.UI.Control inherited from a ControlsCollection (Panel.Controls). Is it possible to upcast from Control to WebControl? Seems silly not to considering the Control is a TextBox or CheckBox which inherits from WebControl. If this isn't possible... how can I access the "Attributes" of a Control? If it were a WebControl, I'd do the following: wc.Attributes["onclick"] = "...

Web resources about - Save image from System.Web.UI.WebControls.Image into database -

Request a demo - Connexus Support

SEO Blog - Search Engine Optimisation / Search Engine Marketing & general IT blog
Read the AKA Marketing search engine optimisation blog for posts about the latest organic search engine optimisation and search engine marketing ...

ALSEDI Group. Excellent Software. Excellent Usability.
ALSEDI Group Portal. High quality Surveillance, Privacy Protection and Desktop Enhancement software.

Case insensitive compare on string in ASP.NET - Coders Grid
using System ; using System.Collections.Generic ; using System.Linq ; using System.Web ; using System.Web.UI ; using System.Web.UI.WebControls ...

Hong Kong 繁体中文 / English China 简体中文 United States English Canada Francais / English Central-South America & Caribbean Region English / Espanol ...

Copyright Information - Media Temple
The (mt) Media Temple ( web site, including all text, HTML, scripts, and images are copyright 1998-2014. All rights reserved. ...

New Microsoft DevRadio Episode: World of Warcraft API Starter Kit for Windows Phone
This is the blog of Dave Isbitski. A Technology Evangelist for Microsoft based out of Philadelphia, PA USA. He is currently focused on helping ...

Adventures in Worstpracticeville
This morning, I wrote ~4500 lines of code in about two minutes. Skeptical? I thought you would be, so here's the curious tale of how I deviated ...

ConditionalRequiredTextValidator Control
The ConditionalRequiredTextValidator control allows you to specify a CheckBox, RadioButton, CheckBoxList, RadioButtonList, DropDownList, or ListBox ...

IT Managed Service Providers with Datacenters in India - Netmagic
As a leading Managed service provider with datacenters in India, Netmagic solutions, fulfills your entire IT infrastructure requirements: from ...

Resources last updated: 12/19/2015 2:23:47 PM