dongyi9023 2015-12-23 03:01 采纳率: 0%
浏览 75
已采纳

使用来自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!

  • 写回答

1条回答 默认 最新

  • dongxie548548 2015-12-23 09:09
    关注

    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; ?>">
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误