Usually web servers do not want you to have more than several thousand images in one folder (recently I had to deal with 70,000 images causing super slow reads and sorts, so trust me with this), therefore, of course, not one folder if you think you will have thousands of images. I would suggest that the best solution would be to remove the Amazon S3 associated with their CDN CloudFront, but if this is unrealistic, you can still do a few things only on your own server.
Create a separate folder for each gallery, as you suggest, only if you know some boundaries of how big the gallery is, and you have an idea of ββhow many galleries will be created. (This is what I would suggest for your specific problem right now)
Put the image name through the hash function, then use the first 1-3 characters of the hash to name the folders for the images. The hash ensures that images are roughly equally divided between folders, and you can decide how many folders you need.
In any case, information about which gallery and image identifier in the actual path are likely to be useful for you, moving forward both in the code and whenever a person should look for errors on the server. I would probably name the folders based on the gallery ID and just make sure that the gallery does not have more than a few thousand images.
source share