Click here to Skip to main content
15,886,567 members
Articles / Programming Languages / C#
Article

store and retrieve image to/from sql server database

Rate me:
Please Sign up or sign in to vote.
1.75/5 (6 votes)
5 Aug 2007 33.4K   24   3
simple save and fetche image toand from database

Introduction

hi.I have a database for save large image and binary data. we use a simple method for save and retrieve image from sqlserver database.

Background

this article useful for every application programmer in related work.

we use this method in LG-iomind company

Using the code

At first we have two main storedprocedure for save and retrieve image

CREATE PROCEDURE sr_fetch_image(@ID int) AS
BEGIN
    SELECT    [Name], Exc, Image_Data
    FROM         [dbimage].[dbo].[tbl_Image]
    WHERE [ID]=@ID
END
GO

CREATE PROCEDURE [sr_insert_Image]
    (
     @Name     [nvarchar](50),
     @Exc     [nvarchar](50),
     @Image_Data     [image])

AS INSERT INTO [dbimage].[dbo].[tbl_Image] 
     (
     [Name],
     [Exc],
     [Image_Data]) 
 
VALUES 
    ( 
     @Name,
     @Exc,
     @Image_Data)
GO

and some code in C# for save and fetching

// Save image in database
OpenFileDialog odlg = new OpenFileDialog();
odlg.ShowDialog();
Cursor.Current = Cursors.WaitCursor;
this.Refresh();
Image bmp=Bitmap.FromFile(odlg.FileName);
System.IO.MemoryStream ms=new System.IO.MemoryStream();
bmp.Save(ms,System.Drawing.Imaging.ImageFormat.Bmp);
sr_fetch_imageTableAdapter.Insert("df", "rer", ms.GetBuffer());
Cursor.Current = Cursors.Default;
// fetch data from database
sr_fetch_imageTableAdapter.Fill(dSMoblie.sr_fetch_image, 3);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
//bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Write(dSMoblie.sr_fetch_image[0].Image_Data, 0, dSMoblie.sr_fetch_image[0].Image_Data.Length);
Image bmp = Bitmap.FromStream(ms);
pictureBox1.Image = bmp;

note that sr_fetch_imageTabelAdapter is my table adapter that have to stored procedure for save and fetching

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Greece Greece
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionhow to call sql server 2005 cursors in vc++ by using ADO Pin
ram on c#11-Nov-07 22:40
ram on c#11-Nov-07 22:40 
GeneralQuestion Pin
thund3rstruck6-Aug-07 2:03
thund3rstruck6-Aug-07 2:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.