Java
75%
前端
40%
Spring
60%
SpringMVC
70%
SpringBoot
80%
Mybatis
60%
数据结构与算法
75%
正在阅读两种方式轻松自制随机图片获取API

两种方式轻松自制随机图片获取API

时间:/评论:1 条评论/阅读:119次

在互联网中,我们常常需要快速获取各类图片资源。今天,就为大家带来一个超实用的教程,教你轻松搭建属于自己的随机图片获取API,从此告别四处寻觅图片API的繁琐。

方法一、外链读取txt

1.新建文件api.php

    <?php
    // 使用__DIR__常量获取当前脚本所在目录,并拼接文件路径
    $filename = __DIR__. '/img.txt';
    if (!file_exists($filename)) {
        die('文件不存在');
    }
    // 打开文件并检查是否成功
    $fs = fopen($filename, "r");
    if (!$fs) {
        die('无法打开文件');
    }
    // 从文本获取链接
    $pics = [];
    while (!feof($fs)) {
        $line = trim(fgets($fs));
        if ($line!== '') {
            array_push($pics, $line);
        }
    }
    fclose($fs);
    // 从数组随机获取链接
    $pic = $pics[array_rand($pics)];
    // 获取type参数
    $type = isset($_GET['type'])? $_GET['type'] : '';
    switch ($type) {
        // JSON返回
        case 'json':
            header('Content - type:text/json');
            die(json_encode(['pic' => $pic]));
        default:
            // 验证链接是否合法
            if (!filter_var($pic, FILTER_VALIDATE_URL)) {
                die('无效的图片链接');
            }
            die(header("Location: $pic"));
    }

2.新建文件img.txt

    http://example.com/image1.jpg
    http://example.com/image2.jpg
    http://example.com/image3.jpg

访问你的网址/api.php访问就可以实现了,api.php和 img.txt 理想存放目录是在同一目录下。
如果将img.txt放于特定目录。此时,需在api.php中修改$filename变量指定完整路径,如:
$filename = '/var/www/wwwroot/data/img.txt';

方法二、读取本地目录模式

    <?php
    $img_array = glob("images/*.{gif,jpg,png}", GLOB_BRACE);
    if (!empty($img_array)) {
        $img = array_rand($img_array);
        $dz = $img_array[$img];
        header("Location: " . $dz);
        exit; // 重定向后终止脚本执行
    } else {
        echo "没有找到符合条件的图片文件。";
    }
    ?>

图片丢到images文件夹下,访问api.php即可

来源:白衣博客

博主关闭了所有页面的评论

收藏域名

xgk.pw 小归客
1314.xyz 一生一世