如何从设置为img src的php文件中返回图像


How to return image from php file set as img src

我正在设置一个随机图像函数,但试图在处理随机发生器之前证明这个概念。

现在我有一个测试.php文件。 它包含:

<?php 
$img = 'http://example.com/img.jpg';
$fp = fopen($img, 'rb');

header('Content-type: image/jpeg;');
header("Content-Length: " . filesize($img));
fpassthru($fp);
exit;
?>

然后在另一个 html 文件中,我<img src="test.php">

目标只是返回图像。 图像 url 工作是正确的,测试.php返回 200。 但是图像只显示了小破碎的图像图标。

我也尝试过readfile()但没有运气。

我只是想展示这张照片。

filesize 不适用于 HTTP URL。文档说:

此函数也可以与某些 URL 包装器一起使用。请参阅支持的协议和包装器以确定哪些包装器支持 stat() 系列功能。

但是,HTTP 包装器不支持 stat 函数。因此,您发送了错误的Content-Length标头,并且您的浏览器无法解释 HTTP 响应。

我看到两种可能的解决方案:

  1. 将图像加载到内存中并使用strlen

    $image = file_get_contents('http://example.com/img.jpg');
    header('Content-type: image/jpeg;');
    header("Content-Length: " . strlen($image));
    echo $image;
    
  2. 使用 $http_response_header 变量读取远程响应的 Content-Length 标头:

    $img = 'http://example.com/img.jpg';
    $fp = fopen($img, 'rb');
    header('Content-type: image/jpeg;');
    foreach ($http_response_header as $h) {
        if (strpos($h, 'Content-Length:') === 0) {
            header($h);
            break;
        }
    }
    fpassthru($fp);
    

另一种选择是使用一些各种内置函数来生成/操作图像 - 在下面的代码中,它是针对 png 的,但 jpg、gif 和 bmp 也存在类似的函数。

使用 url 作为文件路径依赖于主机启用的设置(在开发中显然您可以控制它是否启用)

使用这些函数还可以让你在运行时添加自己的文本,组合图像和各种其他很酷的东西。

<?php
    if( ini_get( 'allow_url_fopen' ) ){
        $imgPath='http://localhost/images/filename.png';
    } else {
        $imgPath=realpath( $_SERVER['DOCUMENT_ROOT'].'/images/filename.png' );
    }
    header("Content-type: image/png");
    $image = imagecreatefrompng($imgPath);
    imagesavealpha($image,true);
    imagealphablending($image,true);
    imagepng($image);
    imagedestroy($image);
?>