让 PHP 页面输出静态图像

Let*_*yer 2 php png image

我希望 PHP 能够根据$_GET[]参数发送 3 个图像中的 1 个。我现在有三个独立的 PNG 图像,并且希望 PHP 脚本将这些图像嵌入其中,然后返回指定的图像。所以,我想要一个 PHP 脚本而不是 3 个图像。这可能吗?我不需要即时创建特殊图像,只需打印其中一张即可。谢谢!

Arc*_*dix 5

如果您的图像位于文件中,请使用 PHP 的readfile()函数,并在输出之前发送内容类型标头:

<?php
$imagePaths = array(
    '1' => 'file1.png',
    '2' => 'file2.png',
    '3' => 'file3.png',
);

$type = $_GET['img'];

if ( isset($imagePaths[$type]) ) {
    $imagePath = $imagePaths[$type];
    header('Content-Type: image/png');
    readfile($imagePath);
} else {
    header('HTTP/1.1 404 File Not Found');
    echo 'File not found.';
}
?>
Run Code Online (Sandbox Code Playgroud)

编辑:
您还可以通过将图像编码为Base64来将图像嵌入到脚本中,然后将它们作为字符串嵌入到 PHP 中,然后使用base64_decode对其进行解码以传递它们:

<?php
$imageData = array(
    '1' => '...', // Base64-encoded data as string
    ...
);

$type = $_GET['img'];

if ( isset($imageData[$type]) ) {
    header('Content-Type: image/png');
    echo base64_decode($imageData[$type]);
} else {
    header('HTTP/1.1 404 File Not Found');
    echo 'File not found.';
}
?>
Run Code Online (Sandbox Code Playgroud)

您还可以使用 PHP 在命令行上对图像进行编码。只需在命令行 ( php script.php image1.png image2.png image3.png > output.php) 中执行此 PHP 脚本并保存其输出,并将其合并到您的脚本中:

<?php
$imageData = array();

foreach ($argv as $index => $imagePath)
    $imageData[(string)($index + 1)] = base64_encode(file_get_contents($imagePath));

echo '$imageData = '.var_export($imageData, true).';';
?>
Run Code Online (Sandbox Code Playgroud)