简体   繁体   English

如何在收藏夹中保存图像并将其加载到图片框

[英]How to save Image in collection and load in picturebox

I declare a list to store image's url 我声明一个列表来存储图像的URL
And call "LoadBitmap" method to get image's stream. 并调用“ 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;
        }

I store image's stream in list . 我将图像的流存储在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); " 但是当程序运行到“ eachPictureBox.Image = Image.FromStream(imageFile); ”时
this line will occurred an error : WebException. 此行将发生错误:WebException。
I also try List<Image> and imageList to store Image then ocurred error again. 我也尝试使用List<Image>imageList来存储Image,然后再次发生错误。
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. 不要处理流,或者将Image存储在列表中,并在需要时使用它。 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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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