C # displays images randomly and one by one

I am creating a simple form-based message display system, each message is a jpeg image, which I want to achieve when the program loads (immediately after user login) one of the jpg is randomly selected and shown, if the user clicks the "Next" button, it is still displayed one jpg until all are displayed. I think I need to read each image in the array, and then randomly select one from the array, and then, when the user clicks the "Next" button, go to the next element of the array. One of the caveats is that I do not want the program to block open jpg files, since others should 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)]);
 }

Thanks a lot Steven

+3
source share
7 answers

Do not 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 do not 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);
    }
}
+3
source

Two things here:

  • Transfer your random instance to a member of the class so that it is created only once.
  • After the image is displayed, delete it from the file array so that only images that you did not display remain in the list. When the list is empty, you know that you have shown everything.
+2
source

Øyvind Bråthen, reset , , ?

0

, 2 :

a) JPG ( ).

b) "tmp" (.. "1.tmp.jpg" ).

"b", , .

, - , .

, , .

:)

0

:

  • ; HashSet<string> , . , NEXT, , . , ( ), . , , . , .
  • , , , Clone(), Dispose() . , .
  • Dispose() , .
0

.

  • jpeg ( , \\Server\Screens\) .

  • . :

  • . , , , PictureBox Image ; .

    , (. @max answer).

  • , . , , , .

0
source
public static int id = 0;
private void timer1_Tick(object sender, EventArgs e)
{
    id = id + 1;
    filelocation = "E:\\example\\" + id + ".bmp";
    pictureBox1.Image = System.Drawing.Bitmap.FromFile(filelocation);
}
0
source

Source: https://habr.com/ru/post/1784495/


All Articles