Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

Generate random image by url

Writer Matthew Harrington

I have an API with the endpoints:

  • api/image/1 Returns me the image 1
  • api/image/random Gives me a random image

Whenever I make a call for a random image, like 5 times on 1 webpage, each time it's the same image. It's a little bit like ...

I would like to have a random image, each time. Even if I call for a random image 10 times on 1 webpage. Is there a way that this is possible?

3

6 Answers

As stated in this github issue, you can basically use .

<img src="" />
<img src="" />
<img src="" />

They actually address this common issue in their documentation. Interestingly, you're using their recommendation to achieve the complete opposite:

Static Random Image
Get the same random image every time based on a seed, by adding /seed/{seed} to the start of the URL.

Solution

According to Picsum, you could do:

To request multiple images of the same size in your browser, add the random query param to prevent the images from being cached:<img src="">
<img src="">

Which results in:

Additionally, you can always get a list of URLs using their API, it allows you to define the number of images and many more things. I would suggest to actually read the small guide they put up on their site

0

Here is most popular and stable API, Simple and easy to use, which will redirect you to random image every single time.

URL

Syntax

Here is JS trick to get unique image on every request

()}

This is caused by browser caching as your are effectively requesting the same image, this can be seen in this screen grab from my browser,

Two lines of code,

<img src="">
<img src="">

One server request,

enter image description here

Depending on what language you are using you will need to add some element of random to the url,

<img src=" echo microtime(); ?>" >
<img src=" echo microtime(); ?>">

I have added microtime() here in PHP, the use of microtime is significant as using time() will not always provide a different request url if the server and client are quick.

I now get two requests and two images,enter image description here

You need to random the numbers in your url; URL =>

<img id = 'imgShow' />
document.getElementById('imgShow').src = '(200+rand())+'/' + (300 + rand()) +'?random=1';}
function rand(){ return Math.floor(Math.random() * 90)} ;

In seeder/factory of Laravel(PHP) you can use something like:

'url' => '()

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy