用数据库中的图像填充列表

本文关键字:填充 列表 图像 数据库 | 更新日期: 2023-09-27 18:21:21

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

我使用的是SQL Server 2008、Visual Studio 2008、C#窗口应用程序。

这是我的代码:

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

用数据库中的图像填充列表

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

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

这对我来说很好——它从AdventureWorks2012数据库

加载101 ThumbNailPhoto