-> Saving image in sql server

column name photo ,  datatype image

-> c#

with the help of  PictureBox control we can view image in c# then convert the image file into byte below code help you to do this:

controls need:

Picture Box: to view image

4 Buttons: open OpenFileDialog and  browse image from system, clear picture box, save into database and open from database

2 TextBox: Enter the name for save and open

OpenFileDialog: to browser image from system

 

code Behind:

// Browse Button

private void btnBrowserImage_Click(object sender, EventArgs e)
{
OpenFileDialog fileChooser = new OpenFileDialog();

fileChooser.Filter = “Image Files (.jpg; .bmp; .gif; .png)|*.jpg; *.bmp; *.png”;

if (fileChooser.ShowDialog() == DialogResult.OK)
{
picBoxEmpImages.ImageLocation = fileChooser.FileName;

imgData=conver_byte(picBoxEmpImages.ImageLocation);

photo = imgData;
}
}

// Convert image to byte

public byte[] conver_byte(string img)
{

imgData = File.ReadAllBytes(img);

return imgData;
}

// Button Clear

private void btnClearImage_Click(object sender, EventArgs e)
{
picBoxEmpImages.ImageLocation = “”;
}

// Button Save

private void btnSaveImage_Click(object sender, EventArgs e)
{

query = “INSERT INTO Image ([Name],[Photo]) values (@name,@photo)”;

cmd = new SqlCommand(query, conn);

cmd.Parameters.Add(“@name”, SqlDbType.Image).Value =txtSaveName;

cmd.Parameters.Add(“@photo”, SqlDbType.Image).Value = photo ;

try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
retVal = cmd.ExecuteNonQuery();
}
else
{
retVal = cmd.ExecuteNonQuery();
}
}
catch (Exception)
{
retVal = 0;
}

finally
{
conn.Close();
}
return retVal;
}

 

//open Button

private void btnOpenImage_Click(object sender, EventArgs e)
{

query = “SELECT * FROM Image WHERE Name=’ ” +txtOpenName+” ‘ “;

try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
adp = new SqlDataAdapter(query, conn);
dt = new DataTable();
adp.Fill(dt);
}
else
{
adp = new SqlDataAdapter(query, conn);
dt = new DataTable();
adp.Fill(dt);
}
}

catch (Exception)
{
dt.Dispose();
}

finally
{
conn.Close();
}

photo = (byte[])dt.Rows[0]["Photo"];

convertImage(photo);

}

 

//convert to image

public Image convertImage(Photo)
{
byte[] byteArrayIn = objBOStudents._photo;

MemoryStream ms = new MemoryStream(byteArrayIn);

Image returnImage = Image.FromStream(ms);

picBoxEmpImages.Image = returnImage;

}

thank u

has…

About these ads