[英]How to save Image in collection and load in picturebox
我聲明一個列表來存儲圖像的URL
並調用“ LoadBitmap”方法獲取圖像流。
//this list to store url list
List<string> imageFileList=new List<string>();
//this list to store return image stream
List<Stream> imageFiles = new List<Stream>();
imageFileList.Add("some picture url");
imageFileList.Add("some picture url");
imageFileList.ForEach(delegate(String imgurl)
{
Stream tempFile = LoadBitmap(imgurl);
imageFiles.Add(tempFile);
tempFile.Dispose();
});
private Stream LoadBitmap(string imageUrl)
{
Stream image;
HttpWebRequest request =(HttpWebRequest)WebRequest.Create(imageUrl);
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
image=stream;
}
return image;
}
我將圖像的流存儲在list中。
然后循環將這些流加載到圖片框
foreach (Stream imageFile in imageFileList)
{
PictureBox eachPictureBox = new PictureBox();
eachPictureBox.SizeMode = PictureBoxSizeMode.AutoSize;
//Load Image from resource
eachPictureBox.Image = Image.FromStream(imageFile);
}
但是當程序運行到“ eachPictureBox.Image = Image.FromStream(imageFile);
”時
此行將發生錯誤:WebException。
我也嘗試使用List<Image>
和imageList
來存儲Image,然后再次發生錯誤。
任何人都有解決該問題的想法?
您已經處理了流,然后嘗試從流中獲取圖像。 不要處理流,或者將Image存儲在列表中,並在需要時使用它。 例如,您可以使用以下代碼:
List<Image> images = new List<Image>();
...
using (var s = new System.IO.FileStream(imageFilePath, System.IO.FileMode.Open))
{
images.Add(Image.FromStream(s));
}
然后,當您需要使用圖像時,只需從列表中獲取它即可,例如:
pictureBox1.Image = images[0];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.