PHP 实现随机图像功能

之前发过一篇PHP简单实现一言 / 随机一句功能,既然随机的文字有了,随机图像当然不能落下。

方法一:随机读取文件夹图片API

PHP 随机图像实现的代码超级简单,短短四行就搞定了:

<?php
$img_array = glob('images/*.{gif,jpg,png,jpeg,webp,bmp}', GLOB_BRACE);
if(count($img_array) == 0) die('没找到图片文件。请先上传一些图片到 '.dirname(__FILE__).'/images/ 文件夹');
header('Content-Type: image/png');
echo(file_get_contents($img_array[array_rand($img_array)]));
?>

或者

<?php 
$img_array = glob("imgs/*.{gif,jpg,png}",GLOB_BRACE); 
$img = array_rand($img_array); 
echo '<img alt="'.$img_array[$img].'" src="'.$img_array[$img].'" />'; 
?>

或者

<?php $img=file('img.txt');//txt文件

$url=array_rand($img);//imgtxt文档里面图片API

header("Location:".$img[$url]); ?>

以上的代码会查找 images 目录下的所有图片,并随机挑选出一张显示出来。如果一时找不到好的图片素材,不妨从这下载

链接:https://pan.baidu.com/s/1sl0Zznn 密码:xipq
链接:https://share.weiyun.com/3Ta6gtdE 密码:bh7vkp

方法二:随机读取网址文件夹图片API

<?php
//设置站点地址及图片文件夹
$weburl= 'https://yourdomain.com/random/';
$path = 'bg';

function getImagesFromDir($path) {
    $images = array();
    if ( $img_dir = @opendir($path) ) {
        while ( false !== ($img_file = readdir($img_dir)) ) {
            if ( preg_match("/(\.gif|\.jpg|\.png|\.webp)$/", $img_file) ) {
                $images[] = $img_file;
            }
        }
        closedir($img_dir);
    }
    return $images;
}
function getRandomFromArray($ar) {
    mt_srand( (double)microtime() * 1000000 );
    $num = array_rand($ar);
    return $ar[$num];
}
$imgList = getImagesFromDir($path);
$img = getRandomFromArray($imgList);

header("Location:" . $weburl. $path . '/' . $img);

?>

可以访问https://yourdomain.com/random/bg.php测试一下。

方法三:随机读取图片地址API

<?php

const imageFiles = './img.txt';

$data = file(imageFiles, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (empty($data[0])){
    header('HTTP/1.1 503 Service Unavailable');
    die ('503 Service Unavailable');
}

$id = array_rand($data) + 1;
settype($id,'integer');
if ($id <= 0 || $id > $quantity){
    $id = array_rand($data) + 1;
}

$pic = $data[$id - 1];
header("Location:" . $pic);

?>

方法四:随机读取图片地址API带扩展返回

使用方法

api.php?id=[图片ID]&type=[返回类型]

## 返回指定id的图片:api.php?id=6

## 返回指定id的图片json信息:api.php?id=6&type=json
{“id”:438,”width”:”1536″,”height”:”864″,”url”:”https:\/\/yourdomain.com\/i\/random\/bg\/random006.webp”}

## 返回随机图片总数:api.php?type=quantity

代码

解决同一站点访问随机图片相同的问题

## 在访问连接后面设置参数,参数可以任意,不重复就可以。
bg.php?_r=792
© 版权声明
THE END
如果喜欢,可以【点赞】【分享】【收藏】
点赞14赞赏 分享
评论 共2条
头像
人生坎坎,山山而峦,不过尔尔;心路漫漫,水水而川,如此悠悠
提交
头像

昵称

取消
昵称表情代码图片