Code To Read Image From Database

abelLazm 2 Tallied Votes 247 Views Share

This is the simple code to read an image from the database.

private void button1_Click(object sender, System.EventArgs e) 
{
      if (images.GetRow())
   {
         this.textBox1.Text = images.GetFilename();
         this.pictureBox1.Image = (Image)images.GetImage();
      } 
else 
{
         this.textBox1.Text = "DONE";
         this.pictureBox1.Image = null;
      }
   }
}


public class Images{
   string imageFilename = null;
   byte[] imageBytes = null;

   SqlConnection imageConnection = null;
   SqlCommand imageCommand = null;
   SqlDataReader imageReader = null;

   public Images() {
      imageConnection = new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI");
      imageCommand = new SqlCommand(@"select imagefile, imagedata from imagetable", imageConnection);

      imageConnection.Open();
      imageReader = imageCommand.ExecuteReader();
   }

   public Bitmap GetImage() {
      MemoryStream ms = new MemoryStream(imageBytes);
      Bitmap bmap = new Bitmap(ms);

      return bmap;
   }

   public string GetFilename() {
      return imageFilename;
   }

   public bool GetRow() {
      if (imageReader.Read()) {
        imageFilename = (string) imageReader.GetValue(0);
        imageBytes = (byte[]) imageReader.GetValue(1);
        return true;
      }else {
        return false;
      }
   }

   public void EndImages() {
      imageReader.Close();
      imageConnection.Close();
   }
bahed121 11 Junior Poster in Training

Can you please help in reading images from a folder

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.