how to read an Image from the Database

everyone i hav written some code to read images from the Database in C#.net, but i cant get where the error occurs here. Here's my code is

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);
           }
     else
     {
     }
   }

   public void EndImages() 
   {
      imageReader.Close();
      imageConnection.Close();
   } 

Upvotes: 0

Views: 1086

Answers (2)

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();
} 

Upvotes: 1

Charles Lambert
Charles Lambert

Reputation: 5132

If you call GetImage() before calling GetRow() you are going to get an error. Also the Bitmap class is not accessible across AppDomains (e.g. calling DrawImage() in a different domain than the one that created it)

Upvotes: 0

Related Questions