473,385 Members | 1,465 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Who can tell me how to retrieve and display the image from SQL server database?

here is the way i store my image...
''
Expand|Select|Wrap|Line Numbers
  1. string imageUploaded = "Image";
  2.                 string savePath;
  3.                 string saveFile;
  4.  
  5.  
  6.                 conItem.Close();
  7.                 if (fupload.HasFile)
  8.                 {
  9.                     savePath = Path.Combine(Request.PhysicalApplicationPath, imageUploaded);
  10.                     saveFile = Path.Combine(savePath, itemCount   + ".jpg");
  11.                     fupload.SaveAs(saveFile);
  12.                 }
''

Then, how i can retrieve the image from the database and display it in my form?
Aug 2 '10 #1

✓ answered by PsychoCoder

the image will be returned and needs to be read into a byte array, here's an example of retrieving an image from your table (data type should be image

Expand|Select|Wrap|Line Numbers
  1. public byte[] GetImageFromSQL(string imgName)
  2. {   
  3.     try
  4.     {
  5.         using (MemoryStream stream = new MemoryStream())
  6.         {
  7.             using (SqlConnection connection = new SqlConnection(@"YourConnectionString"))
  8.             {
  9.                 using (SqlCommand command = new SqlCommand())
  10.                 {
  11.                     command.CommandText = "SELECT [YourImageColumn] FROM [YourTable] WHERE [YourImageNameColumn] = @img";
  12.                     command.CommandType = System.Data.CommandType.Text;
  13.                     command.Parameters.AddWithValue("@img", imgName);
  14.                     command.Connection = connection;
  15.                     command.Connection.Open();
  16.  
  17.                     SqlDataReader reader = command.ExecuteReader();
  18.                     byte[] imgBytes = null;
  19.                     while (reader.Read())
  20.                         imgBytes = (byte[])reader[0];
  21.  
  22.                     return imgBytes;
  23.                 }
  24.             }
  25.         }
  26.     }
  27.     catch(Exception ex)
  28.     {
  29.         Response.Write(ex.Message);
  30.         return null;
  31.     }
  32. }
Then to display it

Expand|Select|Wrap|Line Numbers
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3.     byte[] img = GetImageFromSQL("YourImageName");
  4.     Response.ContentType = "image/jpeg";
  5.     Response.BinaryWrite(img);
  6. }
Hope that helps :)

4 2760
PsychoCoder
465 Expert Mod 256MB
the image will be returned and needs to be read into a byte array, here's an example of retrieving an image from your table (data type should be image

Expand|Select|Wrap|Line Numbers
  1. public byte[] GetImageFromSQL(string imgName)
  2. {   
  3.     try
  4.     {
  5.         using (MemoryStream stream = new MemoryStream())
  6.         {
  7.             using (SqlConnection connection = new SqlConnection(@"YourConnectionString"))
  8.             {
  9.                 using (SqlCommand command = new SqlCommand())
  10.                 {
  11.                     command.CommandText = "SELECT [YourImageColumn] FROM [YourTable] WHERE [YourImageNameColumn] = @img";
  12.                     command.CommandType = System.Data.CommandType.Text;
  13.                     command.Parameters.AddWithValue("@img", imgName);
  14.                     command.Connection = connection;
  15.                     command.Connection.Open();
  16.  
  17.                     SqlDataReader reader = command.ExecuteReader();
  18.                     byte[] imgBytes = null;
  19.                     while (reader.Read())
  20.                         imgBytes = (byte[])reader[0];
  21.  
  22.                     return imgBytes;
  23.                 }
  24.             }
  25.         }
  26.     }
  27.     catch(Exception ex)
  28.     {
  29.         Response.Write(ex.Message);
  30.         return null;
  31.     }
  32. }
Then to display it

Expand|Select|Wrap|Line Numbers
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3.     byte[] img = GetImageFromSQL("YourImageName");
  4.     Response.ContentType = "image/jpeg";
  5.     Response.BinaryWrite(img);
  6. }
Hope that helps :)
Aug 2 '10 #2
Prathap
37
Solved
Expand|Select|Wrap|Line Numbers
  1. Imports System.Data.SqlClient
  2. Imports System.Data
  3. Imports System.IO
  4.  
  5.  Public Class Form1
  6.     Dim str As String = "Data Source=NET3\SQLEXPRESS;Initial Catalog=RestPos;Persist Security Info=True;User ID=sa;Password=password"
  7.     Dim con As New SqlClient.SqlConnection
  8.  
  9.     'To open an image from computer
  10.     '-------------------------------
  11.     Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
  12.         OpenFileDialog1.Title = "Please select a file"
  13.         OpenFileDialog1.InitialDirectory = "c:temp"
  14.         OpenFileDialog1.ShowDialog()
  15.         TextBox2.Text = OpenFileDialog1.FileName.ToString  '--->To Show the file path in textbox2
  16.         PictureBox1.ImageLocation = TextBox2.Text  '--->To show selected image in picturebox
  17.     End sub
  18.  
  19.    'To insert selected image into database
  20.    'The datatype of the column in table to store image should be <image>  
  21.    '--------------------------------------------------------------------
  22.     Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
  23.         con.ConnectionString = str
  24.         Dim ms As New IO.MemoryStream()
  25.         PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)
  26.         Dim arrimage() As Byte = ms.GetBuffer
  27.         Dim cmd As New SqlCommand("insert into image (Emp_Image)values(@picture)", con)
  28.         cmd.Parameters.Add(New SqlParameter("@Picture", SqlDbType.Image)).Value = arrimage
  29.         con.Open()
  30.         cmd.ExecuteNonQuery()
  31.         con.Close()
  32.     End Sub
  33.  
  34.     'We have successfully inserted the image into database.
  35.     'Now we want to Retrieve the image from database.
  36.     '-------------------------------------------------
  37.     Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
  38.         Dim stream As New IO.MemoryStream()
  39.         con.Open()
  40.         Dim command As New SqlCommand("select Emp_Image from Image where Emp_Id='" + TextBox3.Text + "'", con) '--->You can give Emp_id instead of Textbox value.
  41.         Dim image As Byte() = DirectCast(command.ExecuteScalar(), Byte())
  42.         stream.Write(image, 0, image.Length)
  43.         con.Close()
  44.         Dim bitmap As New Bitmap(stream)
  45.         PictureBox2.Image = bitmap '--->I have used another picturebox to display image from database.
  46.     End Sub
  47.     'Thats all, You can place a linklabel below the picturebox if you to change photo and update it in database.
Regards,
Prathap
Jan 6 '12 #3
Works like magic. Thank you very much for the posting.
Jan 30 '12 #4
PsychoCoder
465 Expert Mod 256MB
No problem, glad I could help :)
Jan 31 '12 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Wayne Wengert | last post by:
I am trying to build an ASP.NET application which includes the capability to allow users to save pictures to a SQL Server 2000 database table and then later to display selected photos (usually JPG...
0
by: chrispragash | last post by:
Hello Everybody, I have a server control that stores an image in the database as an image datatype. I would like to display this image (may be in an image control) along with other text in a...
2
by: RedSouljaz | last post by:
Hi, How to display image that was saved in database ms sql server 2000 into picture box. The field type that I use in database is Images I can save to database but cannot show from database. ...
3
by: den 2005 | last post by:
Hi everyone, Here is code working on..Trying to insert record with a column with Image or VarBinary datatype in sql database from a existing jpeg image file, then retrieve this image from...
2
by: Rahul | last post by:
while writing an image ... i get the following error my Code ------------------------------------------------------------------- Dim imgStream As New MemoryStream() Dim query As String query =...
1
by: shalini328 | last post by:
I am using ASP.net 1.1 C# and database is MS access.Can you tell me how can i display image from database
48
by: mirianCalin | last post by:
i am doing a site for appliance center.. i need to display all the products that the company offers, but my problem is that i cant display ALL the images in my database.. the first entry on the...
8
by: AnagJohari | last post by:
I would like to of display an the image at a proper position on a browser. I access the image from the database before doing this I stored the image in a database in a byte form. I also make a...
5
by: SafaaDalloul | last post by:
Please I want know How I can Display Image from database randomly when the web page refresh in Asp.net by C# code
9
by: chabbs | last post by:
Hi, I have my form with some combo box and radio button. And i need to display an image based on the selections. I need to display dynamically the image when the selections are made without...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.