Click here to Skip to main content
15,883,961 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I am making an application, that when i click a button, some bitmap pictures load randomly from a specific location and be shown in a pictureBox ! How to do it ?

my code is already like this :


C#
using System;
using System.Threading;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MLP_OCR
{
    public partial class Form1 : Form
    {
        int index = -1;
        List<Image> images;

        public Form1()
        {
            InitializeComponent();
            images = new List<Image>();
            DirectoryInfo di = new DirectoryInfo(@"F:\bmp"); // give path
            FileInfo[] finfos = di.GetFiles("*.bmp", SearchOption.AllDirectories);
            foreach (FileInfo fi in finfos)
                images.Add(Image.FromFile(fi.FullName));
        }

        private async void trainButton_Click(object sender, EventArgs e)
        {
            for (index=-1; index < 1699; index++)
            {
                //index++;
                if (index < 0 || index >= images.Count)
                    index = 0;
                samplePictureBox.Image = images[index];
                await Task.Delay(2);
            }

        }
    }
}
Posted
Updated 26-Feb-19 6:22am
v4

If you're using the Image route, you can create a list of images with List images = new List(); and add each image to it with images.Add(image); for each image.

For Images:

Random random = new Random();
samplePictureBox.Image = images[random.Next(0, images.Count - 1)];
 
Share this answer
 
Comments
Dark Sauron 6-Nov-13 16:18pm    
Thank you, that worked like a charm :-X
Try this:
C#
private Random rand = new Random();
...
public void GetRandomImage()
    {
    string[] files = Directory.GetFiles(@"D:\Temp\", "*.jpg", SearchOption.AllDirectories);
    myPictureBox.Image = Image.FromFile(files[rand.Next(files.Length)]);
    }
 
Share this answer
 
  1. Create a list of image names (you may use the DirectoryInfo.EnumerateFiles method[^] in order to accomplish it).
  2. Pick a random number r, between 0 and (List.Count-1).
  3. Load and show the image corrensponding to the item r of the list.
  4. Wait for button click
  5. Go to point 2.
 
Share this answer
 

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