简体   繁体   中英

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

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 List<Image> and imageList to store Image then ocurred error again.
Anyone has an idea of how to solve this problem?

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))
{
    images.Add(Image.FromStream(s));
}

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

pictureBox1.Image = images[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM