前言

在很久之前我写过一篇关于如何搭建个人随机图片API的文章

链接:https://moyu233.top/archives/pictureapi

本篇内容基于上篇文章

一些基础步骤略过,直接提供代码

这次对图片API进行了优化升级(其实我还没测试)

获取腾讯COS下图片链接,实现上传图床即上传到API的高效处理

支持传递format参数来指定返回特定格式的图片,不传递则默认所有格式

代码内容

<?php
// 腾讯COS链接
$cos_url = 'https://your-cos-bucket.cos.region.myqcloud.com/';

// 获取可选的图片格式参数
$format = isset($_GET['format']) ? strtolower($_GET['format']) : null;

// 获取指定格式的图片列表
$images = array_map(function($value) use($cos_url, $format) {
    $ext = pathinfo($value, PATHINFO_EXTENSION);
    if (!$format || strtolower($ext) === $format) {
        return $cos_url . $value;
    }
}, json_decode(file_get_contents($cos_url . '?delimiter=/&prefix=images/'), true)['CommonPrefixes']);

// 去除空值
$images = array_filter($images);

// 如果没有符合条件的图片,则返回404错误
if (empty($images)) {
    http_response_code(404);
    exit;
}

// 随机获取一张图片
$random_image = $images[array_rand($images)];

// 获取图片类型
$image_type = mime_content_type($random_image);

// 根据图片类型输出不同的Content-Type
header('Content-Type: ' . $image_type);

// 输出图片
readfile($random_image);

【本篇内容编辑测试中…】

Q.E.D.


人生的意义,就是去码头整点薯条!