Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi,
I want to convert image in to binary format using c#.net 2.0 and sql server 2005.please tell me how i will i do this.

thanks
Rakesh Kumar
Posted
Updated 1-Jun-10 20:02pm
v3
Comments
Ankur\m/ 2-Jun-10 2:00am    
While posting the question did you see this on the right hand side:
"A few simple rules when posting your question.
1. Have you searched or Googled for a solution?"

The very first point. And it gives links to CodeProject and Google search for your convenience.
If you would have read it, it would have saved you and us a lot of time.
I hope you will do it next time.

you shuold do this:

using system.io;
using system.data.sqlclient;

public partial class Form1 : Form
{
SqlConnection con = new SqlConnection();
string _path;


//convert Image to binary and save in DB
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{

_path = openFileDialog1.FileName;


InsertInSQL(_path);


}

}

private void InsertInSQL(string _path)
{
con.ConnectionString = Pic.Properties.Settings.Default.ConnectionS;
string strQ = "insert into dbo.PicTBL(Pic)values(@p)";
SqlCommand command = new SqlCommand(strQ,con);
command.Parameters.AddWithValue("@p",ImageToBinary(_path));
con.Open();
command.ExecuteNonQuery();
con.Close();
}

public static byte[] ImageToBinary(string _path)
{
FileStream fS = new FileStream(_path, FileMode.Open, FileAccess.Read);
byte[] b = new byte[fS.Length];
fS.Read(b, 0, (int)fS.Length);
fS.Close();
return b;
}






//Convert Binary to imge and save in a folder



private void button1_Click_1(object sender, EventArgs e)
{


DataTable dt = Rimage();

foreach (DataRow row in dt.Rows)
{
byte[] b = (byte[])row["Pic"];
Image img = BinaryToImage(b);
img.Save("D:\\NewFolder\\" + row["ID"].ToString() + ".jpg");
}


}

private Image BinaryToImage(byte[] b)
{
if (b == null)
return null;


MemoryStream memStream = new MemoryStream();
memStream.Write(b, 0, b.Length);

return Image.FromStream(memStream);

}

private DataTable Rimage()
{
con.ConnectionString = Pic.Properties.Settings.Default.ConnectionS;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from dbo.PicTBL";
cmd.Connection = con;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
con.Open();
adp.Fill(dt);

return dt;

}



}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900