Store images to database
This snippets is explained about, how to store
the image into database.
Description
We can store the images to database in the form of bytes.
Using Memory Stream class, we can read the images as a byte format.
Here i explained the codes in windows applcation.
Following lines of code is used to save the images to memory stream.
//Initializing the memory stream.
MemoryStream tMemoryStream = new MemoryStream();
//PicbxLogo is a control name of the "PictureBox". This save method is used
to save the images to memory stream.
PicbxLogo.Image.Save(tMemoryStream, PicbxLogo.Image.RawFormat);
//Read the image as bytes.
byte[] MyData = tMemoryStream.GetBuffer();
tMemoryStream.Close();
Create the table using following query
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Common](
[CommonID] [int] IDENTITY(1,1) NOT NULL,
[Logo] [image] NOT NULL,
CONSTRAINT [PK_Common] PRIMARY KEY CLUSTERED
(
[CommonID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
Create a stored procedure using this query,
CREATE PROCEDURE [dbo].[SP_Common]
@AppLogo image = NULL
AS
BEGIN
INSERT INTO [dbo].[Common]
(
AppLogo
)
Select @AppLogo
END
Pass the byte values to this stored procedure as follows
con = new SqlConnection();
con.Open();
cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SP_Common";
cmd.Parameters.Add("@AppLogo", SqlDbType.Binary, MyData.Length).Value = MyData;
cmd.ExecuteNonQuery();
con.Close();
Retrieving images from database
SqlConnection con = new SqlConnection("Data Source = DAMODHARAN-PC\\SQLEXPRESS;uid = sa; pwd = sa;database = WebSamples;");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SP_Insert_StoreImage";
cmd.Parameters.Add("@Mode", SqlDbType.Int, 4).Value = 1;
byte[] tImageByte = cmd.ExecuteScalar() as byte[];
MemoryStream tMemoryStream = new MemoryStream(tImageByte);
PicbxLogo.Image=Image.FromStream(tMemoryStream);
Thanks & Regards,
V.M. Damodharan

Hi Mr.damodharan,
Very usefull info..
Thanks for sharing with all of us.
regards,
harshitha