# Thread: Simplest way to show a random image in a pictureBox ?

1. ## Simplest way to show a random image in a pictureBox ?

I tried to load a bunch of pictureBoxes into an array,
and then assign the image from a random element of the array to the picMain.image.
This did not work. I will post the code tomorrow.

In the meantime, what's the simplest way to do this?

2. ## Re: Simplest way to show a random image in a pictureBox ?

Originally Posted by RipVoidWinkle
...In the meantime, what's the simplest way to do this?
Wait for someone with no self respect and in need of a perceived validation of their worth to do it for you in hopes of earning a forum cookie?

3. ## Re: Simplest way to show a random image in a pictureBox ?

Originally Posted by TnTinMN
Wait for someone with no self respect and in need of a perceived validation of their worth to do it for you in hopes of earning a forum cookie?
Technically, that's correct, but probably not all that helpful. After all, I wouldn't care to tackle this particular problem without knowing at least one key point: Do you REALLY want random, or do you want...almost random?

The problem with a true random sequence is that you could get 2, 2, 2, 2. There are times when you really want to get a random sequence, so if 2,2,2,2 comes up, then so be it. However, with a picturebox, you may or may not want a true random sequence. Instead, you may want the sequence to be N, followed by anything that is not N. Or, you may want something that I can't quite put into a single sentence, so I'll use a few: Suppose you have a set of N pictures. You may want to see all N pictures in random order, but no repeats until after you have gone through all N. In other words, if the first picture is 3, then don't show 3 again until you have seen all the others in the set.

So, I would say that there really isn't a simplest way to do this, because the simplest way would probably suck at times.

4. ## Re: Simplest way to show a random image in a pictureBox ?

Originally Posted by TnTinMN
Wait for someone with no self respect and in need of a perceived validation of their worth to do it for you in hopes of earning a forum cookie?
Bad form. No one likes a user who kicks a puppy. Did you expect a forum cookie? Instead you look like a troll, and you're certainly not making vbforums.com look good to a new user. I've lost a lot of respect.

RipVoidWinkle:

You asked a question about a simple problem without displaying much effort on your own. This tends to not get very good responses, and in the worst case attracts people who get excited about finding elaborate ways to make you feel bad about answering the question.

I think your main problem, based on the text alone, is you need to realize a "picture box" and an "image" are two different things. A "picture box" is a control that you use to display an image. You could sort of implement a form where you load an array of PictureBox controls, then randomly pick one of them and add them to the form. But it's better to have one PictureBox that you set the image to randomly.

There's a lot of ways to go about it, but one of the best is to load your images into an array, randomly select an array index, then set the picturebox's Image property to that image:
Code:
```Public Class Form1

Private _rng As New Random()
Private _images() As Image

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim index = _rng.Next(0, _images.Length)
PictureBox1.Image = _images(index)
End Sub

' ==== Everything below here's just to set up the array. ====

Protected Overrides Sub OnShown(e As EventArgs)
MyBase.OnShown(e)

' Loads two images into the image array on startup from an internet site.
_images = New Image() {
ImageFromUrl("http://placebear.com/100/100"),
ImageFromUrl("http://placebear.com/g/100/100")
}
End Sub

Private Function ImageFromUrl(ByVal url As String) As Image
Dim client As New System.Net.WebClient()

Return Image.FromStream(New IO.MemoryStream(bytes))
End Function
End Class```

5. ## Re: Simplest way to show a random image in a pictureBox ?

Originally Posted by Shaggy Hiker
... Suppose you have a set of N pictures. You may want to see all N pictures in random order, but no repeats until after you have gone through all N. In other words, if the first picture is 3, then don't show 3 again until you have seen all the others in the set.

So, I would say that there really isn't a simplest way to do this, because the simplest way would probably suck at times.
I find the concept or implementation of "drawing objects from a hat" pretty simple, but perhaps that is just me.

Just add the images to a List(Of Image) or List(Of Bitmap).
Populate another List(Of Integer) with the numbers 0 to the image list count - 1.
Use an instance of the Random object to choose an index into the List(Of Integer) and get the value stored there.
Remove the value at that index from the List(Of Integer) so you can't choose it again.
Use the value to set the picturebox image to the image stored at that index value.

Very few lines of code and seems straight forward logic to me.

If you had a line of people you wanted to do something on demand you could line them up and give each a number.
You put slips of paper, each with a corresponding unique number on it, in a hat.
You draw the slips of paper from the hat one at a time, and ask the person with that number to do something.

Once you run out of slips of paper, each person, in random order, has done one thing.
Fill the hat with the slips of paper again, and you can go through it again.

Concept is simple. Implementation is pretty simple.

6. ## Re: Simplest way to show a random image in a pictureBox ?

I agree with that approach, but drawing items from a hat is not technically the same as a random sample. I do think that it's probably the the goal of the OP, though, and the simplest random sample wouldn't give that result. A simple random sample would take pick a random number from 0 to N-1 for the set, so it will repeat at times.

7. ## Re: Simplest way to show a random image in a pictureBox ?

Yes, which is Sitten Spynne's code does.
I thought you were offering different alternative interpretations of the OP's post, the last being the drawing from a hat scenario and that one being the possibly "suck at times" approach.

I think both Sitten Spynne's true random version and my draw from the hat version are both fairly simple examples of implementation of those two possible interpretations of what the OP may want.
I think you also stated a third possibility, allowing non-unique selections (a choice can reappear multiple times before all choices are shown), but never the same image twice in a row.
No one has shown code (or describe the logic) for that one, and could be done with a slight modification of the draw from the hat version, (i.e. you do draw the number from the hat and remove it, but you put it back after the next selection, so you are always drawing from an N-1 choice pool after the first selection).

8. ## Re: Simplest way to show a random image in a pictureBox ?

Originally Posted by passel
Yes, which is Sitten Spynne's code does.
I thought you were offering different alternative interpretations of the OP's post, the last being the drawing from a hat scenario and that one being the possibly "suck at times" approach.
No, what I meant was that some of the alternatives would suck at times. For example, if you go with a straight random sample, you will get repeats. If you are showing pictures in a picturebox, a repeat would look like no change at all. THAT would almost certainly be an ugly user experience, despite being technically correct. That's what I meant that some would suck at times.

9. ## Re: Simplest way to show a random image in a pictureBox ?

Originally Posted by Sitten Spynne
Bad form. No one likes a user who kicks a puppy. Did you expect a forum cookie? Instead you look like a troll, and you're certainly not making vbforums.com look good to a new user. I've lost a lot of respect.
Your statement like so many of your posts is factually incorrect as I did not attack the OP. Yet you feel entitled to personally attacked me which is something that is against the forum rules. I know I am not the only member that you attacked in your attempts to promote yourself as the kind, all knowing, arbiter of what is correct and I probably won't be the last.

I really do not expect the moderator to do anything about your behavior as I have previously reported your racist posting and little was done.

As far as "not making vbforums.com look good to a new user" and "you look like a troll", I really question why one that would post the following is even a member of said forum.
Originally Posted by Sitten Spynne
...
Put simply, if you have to start a new .NET project, the only good reason to use VB at this point is "I have to, because my boss said so."

10. ## Re: Simplest way to show a random image in a pictureBox ?

I can be fluent in Spanish and say "I think English is a better technical language". And I might even hang out on Spanish-speaking forums if I held that belief. I've tried C# communities, it turns out they don't attract as many newbies as VB communities. And helping newbies just feels all-around better, sometimes you see them grow in talent over a couple of years then come back and start answering questions themselves. VB's a fun place to start for many people, and can turn into a career (it did for me). Whether it's marketable is a much larger topic and not the point of this thread.

There are posts in my history, like the one you dug up about ASCII, that I'm not so proud of. That tongue-lashing from Shaggy Hiker hurt, and everyone else who jumped on me was right. That was a stupid post and I feel bad for posting it, and it's part of why I don't make a lot of posts anymore. It's irrelevant if I think it was poor taste, the forum told me it was. And they weren't nice about letting me know.

This #4? I'm proud of it. That post you made? That's your ASCII post, the one you should be ashamed of. They stick to your shoes like dog dung, and stink up the room when people remember them like you just did mine. So try not to make more. I'm going to haunt and harass them until either they or I disappear, just like people called me out for making a trash heap of a post.

11. ## Re: Simplest way to show a random image in a pictureBox ?

I'd say that we don't go removing posts that edge towards the line from people who have a good track record. We all say things we regret, and we all say things that get misinterpreted. Considering the thread over in the Forum Feedback, I was not at all surprised at Sitten's response, and in general, I think it's a good policy.

I have a lot of respect for both of you, and tend to trust your judgement. Some responses just won't go over well, and we can all try to do better. You've both had your say. Let this be the end of it.

12. ## Re: Simplest way to show a random image in a pictureBox ?

That's a fair critique, but I did not want someone to write it for me, just point me in the right direction.
Maybe one line of pseudo-code for illustration.

13. ## Re: Simplest way to show a random image in a pictureBox ?

I will post my first attempt code tomorrow. Got home too late tonight.

Thanks for all the tips. I will try them out tomorrow.

14. ## Re: Simplest way to show a random image in a pictureBox ?

Here is what I tried to do, and nothing would appear:

Code:
```Public Class Form1

Public generator As New Random
Public picBoxList As New List(Of PictureBox)
Public p As PictureBox

Private Sub MakeDeck()

p = New PictureBox
p.Image = My.Resources.PIC1
p.Visible = True

p = New PictureBox
p.Image = My.Resources.PIC2
p.Visible = True

'etc.......

End Sub

Public Sub ShowRandomCard()

Dim x As Integer

x = generator.Next(12)
PictureBox1 = picBoxList.Item(x)

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
call MakeDeck()
call ShowRandomCard()
End Sub

End Class```

15. ## Re: Simplest way to show a random image in a pictureBox ?

Though I'm not certain, I think the reason why it is not working is because of this line:
Code:
`PictureBox1 = picBoxList.Item(x)`
You are also still confusing PictureBox with Image, something that Sitten pointed out in post #4.

How I would solve the problem is by first declaring an Array to store all of your Images in My.Resources, then use a Stack to hold the randomly ordered Array values, and reload the Stack as needed. Take a look at this option:
Code:
```Private r As New Random 'Random object to randomly order collection
Private images() As Image = {My.Resources.PIC1, My.Resources.PIC2, My.Resources.PIC3} 'Image Array to store randomly displayed Images

Private Function RandomCard() As Image
'Stack to hold images
Static deck As Stack(Of Image)

'Check if the Stack was just created OR there are no more items left
If deck Is Nothing OrElse deck.Count = 0 Then
'Create a new Stack with the images from the Array randomly ordered
deck = New Stack(Of Image)(images.OrderBy(Function(i) r.Next()).ToArray())
End If

'Return the value from the Stack but also remove it as well
Return deck.Pop()
End Sub

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
'Set the Image property of the PictureBox to a random Image
PictureBox1.Image = RandomCard()
End Sub```

16. ## Re: Simplest way to show a random image in a pictureBox ?

I am not confusing PictureBox with Image.
I create a list of PictureBoxes.
I then assign the main PictureBox to a randomly selected Picturebox in my List.
Apples and apples, right?

17. ## Re: Simplest way to show a random image in a pictureBox ?

This is how I ended up doing it.
Instead of trying to assign PictureBox objects, I just set the Image property.

I still want to know why my first method did not work

Code:
```  Public pics(4) As Image
Public generator As New Random

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
pics(0) = My.Resources.Chrysanthemum
pics(1) = My.Resources.Desert
pics(2) = My.Resources.Hydrangeas
pics(3) = My.Resources.Jellyfish
pics(4) = My.Resources.Koala

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim x As Integer

x = generator.Next(4)
PictureBox1.Image = pics(x)

End Sub```

18. ## Re: Simplest way to show a random image in a pictureBox ?

Originally Posted by RipVoidWinkle
I still want to know why my first method did not work
PictureBox1 = picBoxList.Item(x) doesn't change anything about the original PictureBox1. Instead, you are "stealing" it's variable name to and using it for something else, the pictureBox from the List. What is more, you will no longer be able to refer to your main PictureBox directly in code because you have "stolen" it's variable name. It's confusing, which is why it isn't a good idea to do it that way.

You got away with doing that in your MakeDeck sub, where the variable name p refers to a different (new) picturebox each time. That's because you don't need the variable name p outside the sub. Once the PictureBoxes are in the list you can identify them by their index.

In short, you are now going about it the right way be using a List(Of Image) instead of a List(Of PictureBox).

The PictureBoxes in your list won't be visible anyway at first. You tried setting the Visible property to True but it's already True by default. You have to add each PictureBox to the form's Controls collection (Me.Controls.Add(p)) before it can be displayed. Once you do that, you can Hide or Show individual PictureBoxes (or change their Visible property to False/True) as often as you like. You'll also need to set the initial Location of each PictureBox at some point. You might as well do that in the MakeDeck sub.

BB

19. ## Re: Simplest way to show a random image in a pictureBox ?

I wonder if the code would have worked if I had done Me.Controls.Add(p)
But, I can't reassign an existing GUI object?

20. ## Re: Simplest way to show a random image in a pictureBox ?

Originally Posted by RipVoidWinkle
But, I can't reassign an existing GUI object?
There are basically two kinds of variables: Value types (simple things like Integers and Doubles, that just have a single value), and Reference types (most things, including Forms and Pictureboxes and Images, which have multiple values).

A variable of a Value type contains the actual value, but a variable of a Reference type just holds a pointer to a section of memory that holds all of the values for it.

If you try to assign one Reference type item to another (as you did with PictureBox1 = picBoxList.Item(x) ), it does not copy values across... it just makes the variables point to the same thing as each other, and whatever the first one (PictureBox1 in this case) was referring to before still exists, but is not linked to the variable any more.

You may be thinking that this should apply to the .Image property as well, and it does... but assuming there was no image before, the fact you can't refer to the previous image is not a problem (because there was nothing there). If there was an image before, it should automatically be destroyed at some point because there is nothing referring to it any more (but the picturebox that was originally referred to by PictureBox1 still exists, because the form is still referring to it).

21. ## Re: Simplest way to show a random image in a pictureBox ?

Originally Posted by RipVoidWinkle
I wonder if the code would have worked if I had done Me.Controls.Add(p)
You could do that but there is no point in doing so unless you want to show all the images on the screen, each in its own picture box. Your code still wouldn't "work" as it stands because you still have to set the Image property of the main picture box to an image, for example:
Code:
`PictureBox1.Image = picBoxList(x).Image`
BB

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

Featured

Click Here to Expand Forum to Full Width