天天看點

PHP實作随機圖檔API

作者:yuuid

分享兩種PHP随機圖檔源碼,第一種通路本地圖檔,第二種通路圖檔連結,代碼如下:

<!-- 資源寶分享:www.httple.net -->
<?php
header('Cache-Control:no-cache,must-revalidate');
header('Pragma:no-cache');
header("Expires:0");
header("Access-Control-Allow-Origin:*");
//處理請求輸出資料
//這将得到一個檔案夾中的所有gif,jpg和png圖檔的數組
$rand=rand(0,1);
if($rand){
    $localurl="img/*.{gif,jpg,png}"; //圖檔所在檔案夾
}else{
    $localurl="img/*.{gif,jpg,png}";
}
$img_array=glob($localurl,GLOB_BRACE);
//從數組中選擇一個随機圖檔 
$img=array_rand($img_array);
$imgurl=$img_array[$img];
$https=isset($_GET["https"])?$_GET["https"]:1;
if($https == "true"){
    $imgurl='https://'.$_SERVER['SERVER_NAME'].'/'.$imgurl;
}else{
    $imgurl='http://'.$_SERVER['SERVER_NAME'].'/'.$imgurl;
}
if(isset($_GET["type"])?$_GET["type"]:1=="json"){
    $rTotal='0';
    $gTotal='0';
    $bTotal='0';
    $total='0';
    $imageInfo = getimagesize($img_array[$img]);
    //圖檔類型
    $imgType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));
    //對應函數
    $imageFun = 'imagecreatefrom' . ($imgType == 'jpg' ? 'jpeg' : $imgType);
    $i = $imageFun($img_array[$img]);
    //測試圖檔,自己定義一個,注意路徑
    for($x=0;
    $x<imagesx($i);
    $x++){
        for($y=0;
        $y<imagesy($i);
        $y++){
            $rgb=imagecolorat($i,$x,$y);
            $r=($rgb>>16)&0xFF;
            $g=($rgb>>8)&0xFF;
            $b=$rgb&0xFF;
            $rTotal+=$r;
            $gTotal+=$g;
            $bTotal+=$b;
            $total++;
        }
    }
    $rAverage=round($rTotal/$total);
    $gAverage=round($gTotal/$total);
    $bAverage=round($bTotal/$total);
    $arr=array('ImgUrl'=>$imgurl,'Color'=>"$rAverage,$gAverage,$bAverage");
    echo json_encode($arr);
    exit();
}
//在頁面顯示圖檔位址
//echo $imgurl;
header("location:$imgurl");           
<?php
//資源寶分享:www.httple.net
//存有美圖連結的檔案名img.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"));
}
 
?>