Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

store and retrieve image to/from sql server database

0.00/5 (No votes)
5 Aug 2007 1  
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