让PHP页面输出静态图像 [英] Have a PHP page output a static image

查看:92
本文介绍了让PHP页面输出静态图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望PHP能够发送3个图像中的1个,具体取决于$_GET[]参数.我现在将图像作为三个单独的PNG,并希望PHP脚本将其嵌入其中,然后返回指定的图像.因此,我想要一个PHP脚本而不是3个图像.这可能吗?我不需要即时创建特殊图像,只需打印其中一张即可.谢谢!

I want a PHP to be able to send 1 of 3 images, depending on a $_GET[] parameter. I have the images as three separate PNGs right now, and would like the PHP script to have those embedded in it, then return the specified image. So, I want one PHP script instead of 3 images. Is this possible? I don't need to create special images on the fly, just print out one of those. Thanks!

推荐答案

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

If your images are in files, use PHP's readfile() function, and send a content-type header before outputting it:

<?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.';
}
?>


您还可以通过对图片进行编码(例如将图片)嵌入脚本中为 Base64 ,然后将它们作为字符串嵌入到PHP中,然后使用


You could also embed your images in the script by encoding them e.g. as Base64, then embed them as strings in PHP, then decode it there with base64_decode to deliver them:

<?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.';
}
?>

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

You could also use PHP to encode the image on the command line. Just execute this PHP script in the command line (php script.php image1.png image2.png image3.png > output.php) and save its output, and incorporate it into your script:

<?php
$imageData = array();

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

echo '$imageData = '.var_export($imageData, true).';';
?>

这篇关于让PHP页面输出静态图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆