How to get random images from a folder

keshu
keshu Member Posts: 2

I am making something like a social media website, using cloudinary to store user avatars and other images

when a user dont want to upload a profile pic, i want the default profile avatar to be choosen randomly from a folder in which i have uploaded some cool random avatars

it is possible ? maybe a get request that will give a random image url from that folder

i am using node , express

Best Answer

  • Wissam
    Wissam Member, Cloudinary Staff Posts: 103
    Answer ✓

    Hi @keshu,

    Cloudinary does not provide a built-in feature to randomly select an image from a folder. However, you can achieve this by implementing a few steps in your Node.js and Express application. Here is one way to do it:

    • First, you need to fetch all the images from the folder in Cloudinary. You can use the cloudinary.search method to achieve this. Here is an example code snippet:
    const { resources } = await cloudinary.search
      .expression('folder:<folder_name>')
      .execute();
    
    • Once you have all the images, you can select a random image from the array of images using the Math.random() method. Here is an example code snippet:
    const randomIndex = Math.floor(Math.random() * resources.length);
    const randomImage = resources[randomIndex];
    
    • Finally, you can construct the URL for the random image using the secure_url property of the randomImage object. Here is an example code snippet:
    const randomImageUrl = randomImage.secure_url;
    

    You can then use this randomImageUrl as the default profile avatar for users who don’t upload their profile picture.

    Please note that this is a basic implementation and you might need to handle errors and edge cases as per your application's requirements.

    I hope this helps! Let me know if you have any other questions.

    Regards,

    Wissam

Answers

  • keshu
    keshu Member Posts: 2

    Hello @Wissam ,

    Thanks for your answer

    If Cloudinary doesnt allow random selection of images then I guess this will be a cool feature to be added, what do you think ?

  • Wissam
    Wissam Member, Cloudinary Staff Posts: 103

    Hi @keshu ,

    Thank you for your feedback.

    I understand that you would like to have a feature that allows a random selection of images from a folder, but as I have suggested it is more a functionality in your application code. This would allow you to have more control over the selection process and customize it to your specific needs.

    I hope it makes sense.

    Regards,

    Wissam

  • rlux
    rlux Administrator, Cloudinary Staff Posts: 68