Yich Lin Yich Lin - 9 months ago 35
C# Question

How to save Image in collection and load in picturebox

I declare a list to store image's url

And call "LoadBitmap" method to get image's stream.

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

private Stream LoadBitmap(string imageUrl)
Stream image;
HttpWebRequest request =(HttpWebRequest)WebRequest.Create(imageUrl);

using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())

return image;

I store image's stream in list .

Then loop to load these stream in picturebox

foreach (Stream imageFile in imageFileList)
PictureBox eachPictureBox = new PictureBox();
eachPictureBox.SizeMode = PictureBoxSizeMode.AutoSize;
//Load Image from resource
eachPictureBox.Image = Image.FromStream(imageFile);

But when program run to "
eachPictureBox.Image = Image.FromStream(imageFile);

this line will occurred an error : WebException.

I also try
to store Image then ocurred error again.

Anyone has an idea of how to solve this problem?

Answer Source

You have disposed the stream and then you are trying to get the image from stream. Don't dispose the stream or Instead store Image in the list and use it when you need. For example you can use such code:

List<Image> images = new List<Image>();
using (var s = new System.IO.FileStream(imageFilePath, System.IO.FileMode.Open))

Then when you need to use the image, simply get it from the list, for example:

pictureBox1.Image = images[0];