473,888 Members | 1,662 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Retrieving images from MS SQL databse

6 New Member

Im using a MS SQL server to store images... Im creating a windows form application using C#.

I need to store and retrieve images from the database.

This is my code to store images:

Expand|Select|Wrap|Line Numbers
  1.              pictureBox.Image = new  System.Drawing.Bitmap(this.openFileDialog.FileName);
  2.              MemoryStream mstr = new MemoryStream();
  3.              pictureBox.Image.Save(mstr, pictureBox.Image.RawFormat);
  4.              byte[] arrImage = mstr.GetBuffer();
  5.              Console.WriteLine("----------"+arrImage.ToString()+"--------------");
  7.             string connString = SatSmart.Misc.DataConn.connString;
  8.             string qry = "update " + this.screenObject.loggedInUserType + "s set photo='@Pic' where userName='" + this.screenObject.loggedInUserName + "';";
  9.             System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection(connString);
  10.             System.Data.Odbc.OdbcCommand cmd = new System.Data.Odbc.OdbcCommand(qry, conn);
  11.             System.Data.Odbc.OdbcParameter param=new System.Data.Odbc.OdbcParameter("@Pic",System.Data.Odbc.OdbcType.Image);
  12.             param.Value = arrImage;
  13.             cmd.Parameters.Add(param);
  14.             conn.Open();
  15.             cmd.ExecuteNonQuery();
  16.             conn.Close();
This loading image code works fine...

Here is my code for retrieving images:

Expand|Select|Wrap|Line Numbers
  1. while (reader.Read())
  2.             {
  4.                 byte[] image = (byte[])reader.GetValue(reader.GetOrdinal("photo"));
  5.                 System.Drawing.Image newImage = null;
  6.                 using (System.IO.MemoryStream stream = new System.IO.MemoryStream(image))
  7.                 {
  8.                     try
  9.                     {
  10.                         newImage = System.Drawing.Image.FromStream(stream);
  11.                     }
  12.                     catch (Exception e)
  13.                     {
  14.                         System.Windows.Forms.MessageBox.Show(e.ToString());
  15.                     }
  16.                 }
  17.                 this.pictureBox.Image = newImage;
  18.             }
this code doesnt work.Im getiing a exception...
The Exception stack trace is....
A first chance exception of type 'System.Argumen tException' occurred in System.Drawing. dll
at System.Drawing. Image.FromStrea m(Stream stream, Boolean useEmbeddedColo rManagement, Boolean validateImageDa ta)
at System.Drawing. Image.FromStrea m(Stream stream)
at SatSmart.Teache rGUI.MyAccountU serControl..cto r(screen screen) in C:\Documents and Settings\san.ba k\Desktop\SatSm art\SatSmart\Te acherGUI\MyAcco untUserControl. cs:line 94

Its a "System.Argumen tException:Para meter is not valid"

Plz help... Im really stuck in this.....
Dec 15 '07 #1
1 2448
6 New Member
I got it finally...

Here are the code snippets....

To upload image:

Expand|Select|Wrap|Line Numbers
  1. MemoryStream mstr = new MemoryStream();
  2.                 pictureBox.Image.Save(mstr, pictureBox.Image.RawFormat);
  3.                 byte[] picbyte = mstr.GetBuffer();
  4.                 conn.Open ();
  5.                 string qry = "INSERT INTO images(imageData) values(?)";
  6.                 System.Data.Odbc.OdbcCommand cmd= new System.Data.Odbc.OdbcCommand(qry, conn);
  7.                 cmd.Parameters.AddWithValue("@Picture", System.Data.Odbc.OdbcType.Image);
  8.                 cmd.Parameters["@Picture"].Value = picbyte;
  9.                 cmd.ExecuteNonQuery();
To download image:

Expand|Select|Wrap|Line Numbers
  1. string qry="select imageData from images where imageId=?";
  2.                 System.Data.Odbc.OdbcCommand cmd= new System.Data.Odbc.OdbcCommand(qry, conn);
  3.                 cmd.Parameters.Add("@ID", System.Data.Odbc.OdbcType.Int, 4);
  4.                 cmd.Parameters["@ID"].Value = reader.GetInt32(reader.GetOrdinal("imageId"));
  5.                 conn.Open();
  6.                 byte[] barrImg=(byte[])cmd.ExecuteScalar();
  7.                 string strfn=Convert.ToString(DateTime.Now.ToFileTime());
  8.                 FileStream fs=new FileStream(strfn, 
  9.                                   FileMode.CreateNew, FileAccess.Write);
  10.                 fs.Write(barrImg,0,barrImg.Length);
  11.                 fs.Flush();
  12.                 fs.Close();
  13.                 this.pictureBox.Image = Image.FromFile(strfn);
Dec 15 '07 #2

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

Similar topics

by: Alec | last post by:
Newbie question. I have a database for displaying the names of bed and breakfasts searched for by the town they are in as below. <?php $result = @mysql_query ("SELECT name FROM site01_details WHERE town='$townsearch' AND code='sleep'"); while ($row = mysql_fetch_array($result))
by: Roman Kagan | last post by:
Hi everyone, I am successful in retrieving the image from the table (.TIF), however, the retrieved file does not work. It looks like an image file - extension, size and all, but the image is not visible. Any ideas? I'm including the first few lines (image opened with Notepad) of the file below. Please, help. """""
by: Dirk Vervecken | last post by:
Hi, i'm having a bit af trouble with a datarepeater of mine. It shows the data that I want, but i've also implemented an Imagebutton that, when clicked, needs to retrieve the information from the line I clicked so it can be altered. This is the HTML code of the repeater: <asp:Repeater id=repArticles runat="server"> <HeaderTemplate>
by: Sirplaya | last post by:
I am retrieving images that I stored in SQL Server on my web pages in C#. I have no problem with the images displaying, however, I am trying to wrap the image with an <A HREF ..." and each time I try, it acts like the link is not even on the image. What is the proper way to do this? Thanks.
by: charlesg | last post by:
I am seriously i need for a solution to this problem fast.I have just inherited an SQL server DB where the images were stored in the database using a table mandatepictures.The images column is called pictures and the data type is binary.From information i have gathered from this forum and the problems i see on ground, i have decided that the way to go is to store this images on the filesystem and refernce the path on a databse table field. The...
by: lmwasisebe | last post by:
hie guys i having problems retrieving xml values, this is the structure of the problem: I have a database with the following fields, 1)id 2)state 3)request. the request field contains a xml file converted to a string. the problem now is that i have to retrieve certain values from that xml string in the request field and save the in some other databse please assist
by: Bjorn Sagbakken | last post by:
This is kind of silly, but I just cannot figure out why: In ASP.NET 2.0 I am retrieving images from a MS SQL server, and writing them as binary to a separate page as the url for image controls, everything by the book. I have been doing this a lot with VB. Now I am writing a new application in C#, and the strange thng is this: - it works well in debug mode - but not on the published folder on the same server (localhost) - image frames...
by: bmallett | last post by:
First off, i would like to thank everyone for any and all help with this. That being said, I am having a problem retrieving/posting my dynamic form data. I have a form that has multiple options within options. I have everything being dynamically named from the previously dynamically named element. (I hope this makes sense.) I am not able to retrieve any of the dynamically created values. I can view them on the source page but can't pull them...
by: shivapadma | last post by:
i have inserted the image into database using the following code String driverName = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/"; String dbName = "hibernatetutorial"; String userName = "root"; String password = "root";
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.