使用来自dir(php)的随机图像的srcset

使用来自dir(php)的随机图像的srcset

问题描述:

I'm looking for a way to use the responsive image attribute 'srcset' alongside php. I'm currently using the following code in order to pick a random image from a directory on the server:

<?php
$dir = "img/";
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
?>

<img src="img/<?php echo $images[$i]; ?>" alt="image">

I've created different versions of the images in the directory with a suffix (i.e., image-1-small.jpg, image-1-big.jpg ... image-2-small.jpg, image-2-big.jpg etc.).

How would I implement the srcset attribute into the php string? I'm looking for an output similar to this:

<img sizes="100vw" srcset="img/image-1-small.jpg 400w, img/image-2-medium.jpg 800w, img/image-1-big.jpg 1600w" src="img/image-1-small.jpg" alt="image-1">

Thanks!

我正在寻找一种方法来使用响应式图像属性'srcset'和php。 我目前正在使用以下代码从服务器上的目录中选择一个随机图像: p>

 &lt;?php 
 $ dir =“img /”;  
 $ images = scandir($ dir); 
 $ i = rand(2,sizeof($ images)-1); 
?&gt; 
 
&lt; img src =“img /&lt;?php echo  $ images [$ i];?&gt;“  alt =“image”&gt; 
  code>  pre> 
 
 

我在目录中使用后缀创建了不同版本的图像(即图像-1小 .jpg,image-1-big.jpg ... image-2-small.jpg,image-2-big.jpg等。) em>。 p>

我该怎么办? 将srcset属性实现到php字符串中? 我正在寻找类似于此的输出: p>

 &lt; img sizes =“100vw”srcset =“img / image-1-small.jpg 400w,img / image  -2-medium.jpg 800w,img / image-1-big.jpg 1600w“src =”img / image-1-small.jpg“alt =”image-1“&gt; 
  code>  pre  > 
 
 

谢谢! p> div>

You can try something like this:

<?php
$dir = "img/";
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
// Get image file name.
$image_name_full = $images[$i];
// Define display types.
$image_display_types = array("-small.jpg", "-medium.jpg", "-big.jpg");
// Remove image display type from image name.
$image_name = str_replace($image_display_types, "", $image_name_full);
?>

<img sizes="100vw" srcset="img/<?php echo $image_name; ?>-small.jpg 400w, img/<?php echo $image_name; ?>-medium.jpg 800w, img/<?php echo $image_name; ?>-big.jpg 1600w" src="img/<?php echo $image_name; ?>-small.jpg" alt="<?php echo $image_name; ?>">