Generate random image by url

35,792

Solution 1

As stated in this github issue, you can basically use https://source.unsplash.com/random/200x200?sig=incrementingIdentifier.

<img src="https://source.unsplash.com/random/200x200?sig=1" />
<img src="https://source.unsplash.com/random/200x200?sig=2" />
<img src="https://source.unsplash.com/random/200x200?sig=3" />

Solution 2

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.

https://picsum.photos/seed/picsum/200/300

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="https://picsum.photos/200/300?random=1">
<img src="https://picsum.photos/200/300?random=2">

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

Solution 3

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

URL

https://source.unsplash.com/random/300x200

Syntax

https://source.unsplash.com/random/<width>x<height>

Here is JS trick to get unique image on every request

https://source.unsplash.com/random/300x200?sig=${Math.random()}

Solution 4

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="https://picsum.photos/200/300">
<img src="https://picsum.photos/200/300">

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="https://picsum.photos/200/300?nocache=<?php echo microtime(); ?>" >
<img src="https://picsum.photos/200/300?nocache=<?php 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

Share:
35,792
user1141796
Author by

user1141796

Updated on July 09, 2022

Comments

  • user1141796
    user1141796 almost 2 years

    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 https://picsum.photos/seed/picsum/200/300...

    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?