C# display images randomly and one after another
Solution 1
Don't use Bitmap.FromFile
, use Bitmap.FromStream
:
using(var fs = new FileStream(files[rand.Next(files.Length),
FileMode.Open, FileAccess.Read))
{
pictureBox1.Image = System.Drawing.Bitmap.FromStream(fs);
}
I don't know how to create an array of images
var files = Directory.GetFiles("\\\\server\\screens\\", "*.jpg");
var images = new Image[files.Length];
for(int i = 0; i < files.Length; ++i)
{
using(var fs = new FileStream(files[i], FileMode.Open, FileAccess.Read))
{
images[i] = System.Drawing.Image.FromStream(fs);
}
}
Solution 2
Two things here:
- Move your random instance out to a class member so that it wil only be instantiated once.
- After you display the image, remove it from the files array so that only the images you have not shown remain in the list. When the list is empty, you know you have shown them all.
Steve Wood
Updated on June 04, 2022Comments
-
Steve Wood over 1 year
I am creating a simple form based message display system, each message is a jpeg image, what I want to achieve is when the program loads (just after a user has logged on) one of the jpg's is randomly selected and shown, if the user clicks the Next button another jpg is shown until all have been displayed. I think I need to read each image into an array and then randomly select one from the array and then when a user clicks Next move on to the next item in the array. One caveat is that I don't want the program to lock open the jpg files as others need to be able to delete them.
My current code is below, I would appreciate any help and advice you can offer.
private void Form1_Load(object sender, EventArgs e) { var rand = new Random(); var files = Directory.GetFiles(@"\\server\screens\", "*.jpg"); pictureBox1.Image = System.Drawing.Bitmap.FromFile(files[rand.Next(files.Length)]); } private void buttonNextImage_Click(object sender, EventArgs e) { var rand = new Random(); var files = Directory.GetFiles(@"\\server\screens\", "*.jpg"); pictureBox1.Image = System.Drawing.Bitmap.FromFile(files[rand.Next(files.Length)]); }
Many thanks Steven