如何从数据库中读取图像

时间:2011-04-11 05:32:38

标签: c# database

每个人我都写了一些代码来从C#.net中的数据库中读取图像,但是我无法在这里找到错误。这是我的代码

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

如果在调用GetRow()之前调用GetImage(),则会出现错误。此外,无法通过AppDomains访问Bitmap类(例如,在与创建它的域不同的域中调用DrawImage())