为什么在图像列表上循环定时器滴答事件时抛出异常参数无效?

Why when looping in timer tick event over images list it's throwing exception parameter is not valid?

System.ArgumentException: 'Parameter is not valid.'

private void timer1_Tick(object sender, EventArgs e)
        { 
            for (int i = 0; i < myGifList.Count; i++)
            {
                Bitmap bmp = new Bitmap(myGifList[i]);
                pictureBox1.Image = bmp;
                bmp.Dispose();
            }
        }

循环结束后抛出异常。

在那之前我做了:

private void timer1_Tick(object sender, EventArgs e)
        { 
            for (int i = 0; i < myGifList.Count; i++)
            {
                pictureBox1.Image = new Bitmap(myGifList[i]);
            }
        }

但随后抛出内存不足异常。

首先我第一次尝试这个:

int counter = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if(counter == 10)
            {
                counter = 0;
            }

            for (int i = 0; i < myGifList.Count; i++)
            {
                Bitmap bmp = new Bitmap(myGifList[counter]);
                pictureBox1.Image = bmp;
            }

            counter++;
        }

这是有效的,图像在 pictureBox1 中循环,但一段时间后它抛出内存不足异常。

完整代码:

我正在下载图像,然后将图像读回列表,然后尝试将它们显示在 picutreBox1 中,并使用 trackBar1 通过计时器更改 pictureBox1 中图像的循环速度。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Extract
{
    public partial class Form1 : Form
    {
        List<string> myGifList = new List<string>();

        public Form1()
        {            
            List<string> times = new List<string>();
            string t = "";

            InitializeComponent();

            using (WebClient client = new WebClient()) // WebClient class inherits IDisposable
            {
                client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36");
                client.DownloadFile("https://myimages/", @"D:\localfile.html");

                var file = File.ReadAllText(@"D:\localfile.html");

                int idx = file.IndexOf("arrayImageTimes.push");
                int idx1 = file.IndexOf("</script>", idx);

                string results = file.Substring(idx, idx1 - idx);

                var statements = results.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < statements.Length; i++)
                {
                    if (i == 10)
                    {
                        break;
                    }

                    string number = statements[i].Split('\'')[1];

                    times.Add(number); // add to a list instead

                    var link = "https://myimages" + number;
                    client.DownloadFile(link, @"D:\Images\Image" + i + ".jpeg");
                }
            }

            FileInfo[] fi;
            DirectoryInfo dir1 = new DirectoryInfo(@"D:\Images");
            fi = dir1.GetFiles("*.jpeg");
            for (int i = 0; i < fi.Length; i++)
            {
                myGifList.Add(fi[i].FullName);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        int counter = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if(counter == 10)
            {
                counter = 0;
            }

            for (int i = 0; i < myGifList.Count; i++)
            {
                Bitmap bmp = new Bitmap(myGifList[counter]);
                pictureBox1.Image = bmp;
            }

            counter++;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            timer1.Interval = 100 * trackBar1.Value;
        }
    }
}

您似乎在尝试遍历 myGifList,但随后您在方法中硬编码了 10 的值。

然而,更大的问题是您甚至没有使用循环定义的 i,所以您只是无意义地覆盖了相同的 Bitmap myGifList.Count 次- 使您的代码效率低下。

尝试:

private void timer1_Tick(object sender, EventArgs e)
{
   if (counter == myGifList.Count)
      counter = 0;

   pictureBox1.Image?.Dispose();

   Bitmap bmp = new Bitmap(myGifList[counter]);
   pictureBox1.Image = bmp;

   counter++;
}

注意在调用.Dispose():[=时应该使用null conditional operator?来防止可能的NullReferenceException 32=]

pictureBox1.Image?.Dispose();

第一次将图像设置为 pictureBox1.Image 时会发生这种情况 null,导致 .Dispose() 抛出异常。


更好的方法是使用 PictureBox.ImageLocation 属性,这样您就可以显示图像而无需每次都创建 Bitmap 对象:

private void timer1_Tick(object sender, EventArgs e)
{
   if (counter == myGifList?.Count)
      counter = 0;

   pictureBox1.ImageLocation = myGifList[counter];

   counter++;
}

旁注:Timer.Interval 属性 也在 milliseconds 中,所以我会提高 trackBar1_Scroll(...) 中的 100 值,如果你想要真正能够看到循环播放的图像。