1

我想从 SQL 表中检索图像并将其保存在列表中并在我的列表视图中显示。但我不知道该怎么做。我需要你的帮助。

我正在使用 SQL Server 2008、Visual Studio 2008、C# Window 应用程序。

这是我的代码:

cmd = new SqlCommand("Select ScanImage from ScanDocuments", con);
dr = cmd.ExecuteReader();

List<ImageList> lstitem = new List<ImageList>();

while (dr.Read())
{
    ImageList _image = new ImageList();
    byte[] data = (byte[])dr["ScanImage"];

    MemoryStream ms = new MemoryStream(data);
    Image bmp = new Bitmap(ms);

    lstitem.Add(bmp);
}
4

1 回答 1

1

您的代码有几个缺陷 - 您需要使用类似这样的东西:

// define connection string and select statement
// I used AdventureWorks 2012 database - change to match *YOUR* environment
string connectionString = "server=.;database=AdventureWorks2012;integrated security=SSPI;";
string query = "SELECT ThumbNailPhoto FROM Production.ProductPhoto";

// define a list of "Image" objects 
List<Image> listOfImages = new List<Image>();

// using the SqlConnection and SqlCommand ....
using(SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand selectCmd = new SqlCommand(query, conn))
{
     // open connection
     conn.Open();

     // execute SqlCommand to return a SqlDataReader
     using (SqlDataReader rdr = selectCmd.ExecuteReader())
     {
         // iterate over the reader
         while (rdr.Read())
         {
              // load the bytes from the database that represent your image
              var imageBytes = (byte[]) rdr[0];

              // put those bytes into a memory stream and "rewind" the memory stream
              MemoryStream memStm = new MemoryStream(imageBytes);
              memStm.Seek(0, SeekOrigin.Begin);

              // create an "Image" from that memory stream
              Image image = Image.FromStream(memStm);

              // add image to list 
              listOfImages.Add(image);
         }
    }

    conn.Close();
}

这对我来说很好 - 它ThumbNailPhotoAdventureWorks2012数据库中加载 101

于 2013-07-06T21:02:34.993 回答