• 首页
  • 搜索
  • 夜间模式
    ©2026  大白蚁的生活碎碎念 Theme by OneBlog

    大白蚁的生活碎碎念博客

    搜索
    标签
    # 随笔 # 数据库 # typecho # Linux # teamspeak
  • 首页>
  • 学习>
  • 正文
  • 喜欢二次元?用PHP给自己做一个随机调用图片api

    2023年07月10日 4 阅读 0 评论 1801 字

    几句话便实现了一个随机图片获取的接口,动手吧!

    第一步:新建一个文件夹,命名为:img(这个文件里放你需要的图片)
    第二步:新建一个index.php文件,把以下代码填写进去 (这个文件就是api地址)

    <?php
    $img_array = glob("img/*.{webp,gif,jpg,png}",GLOB_BRACE); 
    $img = array_rand($img_array); 
    $dz = $img_array[$img];
    header("Location:".$dz);
    ?>

    方式二

    <?php
    
    function getRandomImageFromDirectory($directory) {
        // 获取目录中的所有文件
        $files = glob($directory . '/*');
    
        // 过滤出图片文件
        $imageFiles = array_filter($files, function($file) {
            $imageExtensions = ['jpg', 'jpeg', 'png', 'gif'];
            $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
            return in_array($extension, $imageExtensions);
        });
    
        // 随机选择一张图片
        $randomImage = $imageFiles[array_rand($imageFiles)];
    
        // 读取图片数据并返回
        $imageData = file_get_contents($randomImage);
        return $imageData;
    }
    
    // 指定目录路径
    $directoryPath = '/path/to/your/directory';
    
    // 获取随机图片数据
    $imageData = getRandomImageFromDirectory($directoryPath);
    
    // 设置 HTTP 头信息,指定返回的内容是图片数据
    header('Content-Type: image/jpeg');
    
    // 输出图片数据
    echo $imageData;
    
    ?>

    方式三

    第一步:创建一个img.txt文件 (这个文件里放你的储存的图片链接,一行一条)
    第二步:新建一个index.php文件,写入以下代码 (这个文件就是api地址)

    <?php
    
    //存有链接的文件名,这里是存放图片链接的txt文件
    $filename = "img.txt";
    if (!file_exists($filename)) {
        die('文件不存在');
    }
    
    //从文本获取链接
    $pics = [];
    $fs = fopen($filename, "r");
    while (!feof($fs)) {
        $line = trim(fgets($fs));
        if ($line != '') {
            array_push($pics, $line);
        }
    }
    
    //从数组随机获取链接
    $pic = $pics[array_rand($pics)];
    
    //返回指定格式
    $type = $_GET['type'];
    switch ($type) {
    
        //JSON返回
        case 'json':
            header('Content-type:text/json');
            die(json_encode(['pic' => $pic]));
    
        default:
            die(header("Location: $pic"));
    }
    本文著作权归作者 [ 大白蚁 ] 享有,未经作者书面授权,禁止转载,封面图片来源于 [ 互联网 ] ,本文仅供个人学习、研究和欣赏使用。如有异议,请联系博主及时处理。
    — END —
    首页
    Copyright©2026  All Rights Reserved.  Load:0.021 s
    Theme by OneBlog V3.6.5
    夜间模式

    开源不易,请尊重作者版权,保留基本的版权信息。