You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于TXT存储的PHP访问计数器 合并数字图片为单图实现外部嵌入

单张访问计数器图片实现方案

核心思路

基于PHP的GD扩展,将计数对应的多张数字素材图片横向拼接为单张完整图片,直接输出图片流,无需返回HTML标签,即可支持第三方页面直接用img标签嵌入使用。

完整实现代码

<?php
// 计数逻辑处理
$countFile = 'visitas.txt';
$currentViews = intval(trim(file_get_contents($countFile)));
$newViews = $currentViews + 1;
file_put_contents($countFile, $newViews);
$digits = str_split((string)$newViews);
if (empty($digits)) $digits = ['0'];

// 数字图片加载与总宽度计算
$digitHeight = 20; // 与你现有数字素材的高度保持一致
$totalWidth = 0;
$digitResource = [];
foreach ($digits as $d) {
    $path = "{$d}.png";
    if (!file_exists($path)) $path = "0.png";
    $img = imagecreatefrompng($path);
    $digitResource[] = $img;
    $totalWidth += imagesx($img);
}

// 创建透明背景画布
$counterImg = imagecreatetruecolor($totalWidth, $digitHeight);
imagesavealpha($counterImg, true);
$transparentBg = imagecolorallocatealpha($counterImg, 0, 0, 0, 127);
imagefill($counterImg, 0, 0, $transparentBg);

// 拼接数字图片
$offsetX = 0;
foreach ($digitResource as $img) {
    $w = imagesx($img);
    imagecopy($counterImg, $img, $offsetX, 0, 0, 0, $w, imagesy($img));
    $offsetX += $w;
    imagedestroy($img);
}

// 输出图片流
header('Content-Type: image/png');
// 若需要输出jpg格式,替换为以下两行:
// header('Content-Type: image/jpeg');
// imagejpeg($counterImg, null, 90);
imagepng($counterImg);
imagedestroy($counterImg);
exit;
?>

使用说明

  • 确保你的PHP环境已开启GD扩展,visitas.txt文件授予读写权限,0.png~9.png数字素材与代码文件放在同一目录
  • 第三方页面直接嵌入即可使用:<img src="https://你的站点域名/对应代码文件名.php">
  • 若要实现示例中的jpg后缀访问格式,可添加伪静态规则:
    • Nginx配置:rewrite ^/img-counter-(\d+)\.jpg$ /你的代码文件名.php last;
    • Apache .htaccess配置:RewriteRule ^img-counter-(\d+)\.jpg$ 你的代码文件名.php [L]

内容的提问来源于stack exchange,提问作者Sophie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:45:01