在没有列出的文件名数组的页面加载中从目录加载随机图像 [英] Load Random Image From Directory on Page Load Without a Listed Array of File Names

查看:75
本文介绍了在没有列出的文件名数组的页面加载中从目录加载随机图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在网站上做了一些调查,每次我提出这个问题的解决方案时,其中一个要求是有一个命名约定和每个图像的列表从目录中提取(例如:image1 .jpg,image2.jpg等)所有文件名都不同,有数千个可供选择(因此将每个文件列为数组中的随机机会不起作用)。

I've done some looking around on the site and every time I pull up a solution to this problem, one of the requirements is to have a naming convention and a list of every image to pull from the directory (example: image1.jpg, image2.jpg, etc.) All of the file names are different and there are thousands of them to pick from (so listing each one as a random opportunity in an array is not going to work).

我通常使用CMS服务,我在记事本中从头开始编写这个网页,试图提高我的编码技能......而且我不知道从哪里开始。我对HTML和CSS很不错,但j Query和JavaScript不是我的朋友哈哈。

I typically use CMS services and I'm writing this webpage from scratch in Notepad in an attempt to better my coding skills... and I'm not sure where to begin. I'm decent with HTML and CSS, but j Query and JavaScript are not my friends haha.

感谢您的帮助! (即使它只是指向我无法找到的教程或解决方案!!!)

Thank you for any help! (Even if it's just pointing me to a tutorial or a solution I could not find!!!)

推荐答案

所以经过很多帮助和社区的指导,我已经找到了答案!为了详细阐述我的过程,我们采取以下措施来实现预期的结果:

So after much help and guidance from the community, I have figured out the answer! To clarify my process in extreme detail, here is what I did to achieve the desired outcome:


  1. 将页面创建为.php文件一个.html文件(在我的例子中,index.php)。如果使用记事本创建文件,请确保将文件扩展名更改为.php,将编码更改为UTF-8,并将文件类型另存为所有文件。据我了解,PHP可以随机选择文件但不能将此信息传递给静态HTML页面。

  2. 将此代码块放入图像应显示的网页中。目前,它被设置为引用根目录(aka mysite.com/images/)中名为images的文件夹。这可以通过在$ imagesDir之后修改撇号之间的文本来更改。如果它在php代码块之外,页面上的所有其他html标记都将正常工作。

代码块:

<?php
   $imagesDir = 'images/';
   $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
   $randomImage = $images[array_rand($images)];
   echo "<img src='$randomImage'>";
?>

感谢@bardizba的代码!虽然可能有较少资源密集的方式来编写它,但我的情况有点不同,因为目录中的文件名不符合命名约定,并且混合了文件类型(jpg,gif等)

Thank you @bardizba for the code! Although there may be less resource intensive ways to write this, my situation was a bit different because the file names in the directory did not follow a naming convention and there was a mix of file types (jpg, gif, etc.)

再次感谢帮助我的每个人!

Thanks again to everyone that helped me out!

这篇关于在没有列出的文件名数组的页面加载中从目录加载随机图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆