将图像从图像阵列逐个加载到图片框。 [英] Load images one by one from an image array to a picture box.

查看:109
本文介绍了将图像从图像阵列逐个加载到图片框。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将图像从图像数组逐个加载到图片框c#中。

但我的问题只是图片框中显示的最后一个元素(图片)。



我尝试了什么:



I need to load images one by one from an image array to a picture box c#.
But my problem is only the last element(picture) is displayed in picture box.

What I have tried:

private void button3_Click(object sender, EventArgs e)
{

    Image image;

    //int counter = 0;
    string[] images = Directory.GetFiles(@"C:\outputDirectory", "*.bmp");


    for (int counter = 0; counter < 10; counter++)
    {
        image = Image.FromFile(images[counter]);
        pictureBox.Width = image.Width;
        pictureBox.Height = image.Height;
        pictureBox.Image = image;
    }
}

推荐答案

那是因为你循环遍历整个数组 - 所有的图像都是被分配到图片框但很快你就看不到了。然后当循环结束时,只有最后一张图片在那里。



您需要在此按钮点击之外加载图像数组并将计数器初始化为0 - 计数器需要在表单级别声明。



在按钮上单击显示图像并递增计数器



这是我的意思的一个例子。在用户发起的事件中一次执行这一张图片的优点是用户可以在他们想要的时候摆脱这个
That is because you are looping through the entire array - all of the images are being assigned to the picture box but so quickly you won''t see them. Then when the loop is finished only the last picture is there.

You need to load the array of images outside of this button click and initialise the counter to 0 - counter will need to be declared at the form level.

In the button click display the image and increment the counter

Here''s an example of what I mean. The advantage of doing this one picture at a time on a user-initiated event is that the User can get out of this when they want to
public partial class Form3 : Form
{
    string[] images = Directory.GetFiles(@"C:\outputDirectory", "*.bmp");
    private int counter = 0;
    private void Form3_Load(object sender, EventArgs e)
    {

    }
    private void button1_Click(object sender, EventArgs e)
    {
        if (images.Length == 0) return;

        var image = Image.FromFile(images[counter]);
        pictureBox.Width = image.Width;
        pictureBox.Height = image.Height;
        pictureBox.Image = image;

        if (++counter >= images.Length) counter = 0;
    }
}


试试这个



try this

for (int counter = 0; counter < images.Length; counter++)  // use the image array length to avoid index exception
           {
               var image = Image.FromFile(images[counter]);
               pictureBox.Width = image.Width;
               pictureBox.Height = image.Height;
               pictureBox.Image = image;

               System.Threading.Thread.Sleep(200); // delay by 0.2 seconds to see the transition 
              Application.DoEvents(); 
           }


这篇关于将图像从图像阵列逐个加载到图片框。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆