从数据库下载图像集,并使用HTTPRequest和HTTPResponse将其显示在Picturebox C#中

时间:2014-03-11 14:36:39

标签: c# sql-server database

首先,在有人说这个问题无效之前,因为我先向Google提出答案并向我提出建议;我在互联网上尝试了几乎所有解决方案,但无法弄清楚下一步该做什么。所以,让我解释一下我的问题。

我有一个数据库(MS SQL 2012)。我已经与该数据库中的一个表建立了连接,如下所示:

 private void button1_Click(object sender, EventArgs e)
    {
        DataTable t1 = new DataTable();
        using (SqlConnection connection = new SqlConnection("myconnectionString"))
        {
            connection.Open();
            using (SqlCommand cm = new SqlCommand("SELECT ID,Filename FROM somedatabase WHERE Type = 'specified multiple types using OR'", connection))
            {
                t1.Load(cm.ExecuteReader());
                foreach (DataRow row in t1.Rows)
                {
                    Console.WriteLine(" ");
                    for (int i = 0; i < t1.Columns.Count; i++)
                    {
                        Console.WriteLine(row[i].ToString() + " ");
                    }

                }


            }
        }
    }

上面的代码位于某个button1_click()下,并且工作正常。现在我真正的问题是,我想将此表中的图像显示到PictureBox中。我现在正在尝试的内容如下:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://somelink");
                 request.Method = "GET";
                 request.ContentType = "application/x-www-form-urlencoded";
                 request.CookieContainer = container;


                 response = (HttpWebResponse)request.GetResponse();
                 Stream stream = response.GetResponseStream();

                 byte[] buffer = new byte[100000];
                 int read, total = 0;

                 while((read = stream.Read(buffer,total, 1000)) != 0)
                 {
                     total += read;
                 }

                 Bitmap bmp = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer,0,total));
                 pictureBox1.Image = bmp;

以上代码位于不同的button_click()下。没有错误,警告或任何东西。但点击按钮后,图片框中没有任何内容。任何有关此问题的帮助将受到高度赞赏。谢谢。

1 个答案:

答案 0 :(得分:0)

代码工作得很好。唯一需要的更改是byte []数组的大小。它设置为字节[100000]但是,需要将其设置为更高的值,因为我尝试访问的图像具有更高的分辨率,因此尺寸更大。谢谢大家的帮助。