using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient; // to work with sqlserver we have to use this
using System.IO; //to work with files we have to use this
namespace WindowsApplication2
{
public partial class Form1 : Form
{
//
Image img;
string curfilename;
string cs = "Data Source=.;Initial Catalog=stud;Integrated Security=True;Pooling=False"; //creating an connection string to connect to database
public Form1()
{
InitializeComponent();
}
private void image_retrival (object sender, EventArgs e) //retriving image from a database
{
if (textBox1.Text != "")
{
string s = "select photo from picture_demo where name='" + textBox1.Text + "' "; //qurry to retrive picture from database by a condiction
SqlConnection c = new SqlConnection(cs); //creating an object of the sqlconnection class
try
{
c.Open(); // sqlconnection is opened
FileStream f;
BinaryWriter b;
int bufsize = 100;
byte[] obyte = new byte[bufsize]; // creating an byte array inorder to retrive and store image
long rtv;
long stindx = 0;
string sdi = textBox1.Text;
SqlCommand cmd = new SqlCommand(s, c); //creating an object to sqlcommand
SqlDataReader sdr = cmd.ExecuteReader(); // creating an object to sqldatareader
while (sdr.Read()) // loop for reading data in the database
{
f = new FileStream(sdi, FileMode.OpenOrCreate, FileAccess.Write);
b = new BinaryWriter(f);
stindx = 0;
rtv = sdr.GetBytes(0, stindx, obyte, 0, bufsize); //this method is importent to retrive image from deatabas
while (rtv == bufsize)
{
b.Write(obyte);
b.Flush();
stindx += bufsize;
rtv = sdr.GetBytes(0, stindx, obyte, 0, bufsize);
}
b.Flush();
b.Close();
f.Close();
// b.Write(obyte, 0, (int)rtv - 1);
// b.Flush();
// b.Close();
// f.Close();
}
//c.Close();
img = Image.FromFile(sdi);
pictureBox1.Image = img;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
c.Close();
}
}
}
private void browse(object sender, EventArgs e) //this section is used to select an image from our computer
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
curfilename = openFileDialog1.FileName;
pictureBox1.ImageLocation = curfilename;
}
}
private void submit(object sender, EventArgs e) // method is used to save an image to a database
{
if (openFileDialog1.FileName != "")
{
FileStream f = new FileStream(curfilename, FileMode.OpenOrCreate, FileAccess.Read);
byte[] rawdata = new byte[f.Length];
f.Read(rawdata, 0, Convert.ToInt32(f.Length));
f.Close();
SqlConnection c = new SqlConnection(cs);
try
{
c.Open();
SqlCommand cmd = new SqlCommand("insert into picture_demo values('" + textBox1.Text + "'," + " @pic)", c);
cmd.Parameters.Add("@pic", SqlDbType.Image).Value = rawdata;
SqlDataReader sdr = cmd.ExecuteReader();
MessageBox.Show("record entered");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
c.Close();
}
}
}
No comments:
Post a Comment