Click here to Skip to main content
15,893,668 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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:

C#
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;
    }
}
Posted
Updated 1-Jun-16 3:11am
v2
Comments
Philippe Mori 1-Jun-16 9:14am    
And you expect what?

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
C#
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;
    }
}
 
Share this answer
 
v2
try this

C#
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(); 
           }
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900