Are you considering the fact that when you show an image on a page the code for the page is always generated first. That is then sent to the user, and their browser requests the image. So the image is not generated until the user already has the HTML bit..
Therefore you'll need to generate the random number in the script that builds the HTML, put it in the session, and then use the number in the session in your image generation script.
But you may already be considering that. How about showing us some code so we can figure out whats going awry?