将 PHP 页面作为图像返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/900207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:15:36  来源:igfitidea点击:

Return a PHP page as an image

phpimage-processinghttp-headersmime-types

提问by MichaelICE

I am trying to read a image file (.jpeg to be exact), and 'echo' it back to the page output, but have is display an image...

我正在尝试读取图像文件(确切地说是 .jpeg),并将其“回显”回页面输出,但是显示图像...

my index.php has an image link like this:

我的 index.php 有一个像这样的图片链接:

<img src='test.php?image=1234.jpeg' />

and my php script does basically this:

我的 php 脚本基本上是这样的:

1) read 1234.jpeg 2) echo file contents... 3) I have a feeling I need to return the output back with a mime-type, but this is where I get lost

1) 读取 1234.jpeg 2) 回显文件内容... 3) 我觉得我需要用 mime 类型返回输出,但这是我迷路的地方

Once I figure this out, I will be removing the file name input all together and replace it with an image id.

一旦我弄清楚这一点,我将一起删除输入的文件名并将其替换为图像ID。

If I am unclear, or you need more information, please reply.

如果我不清楚,或者您需要更多信息,请回复。

回答by Martin Geisler

The PHP Manual has this example:

PHP 手册有这个例子

<?php
// open the file in a binary mode
$name = './img/ok.png';
$fp = fopen($name, 'rb');

// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));

// dump the picture and stop the script
fpassthru($fp);
exit;
?>

The important points is that you must send a Content-Type header. Also, you must be careful not include any extra white space (like newlines) in your file before or after the <?php ... ?>tags.

重要的一点是您必须发送一个 Content-Type 标头。此外,您必须注意不要在<?php ... ?>标签之前或之后的文件中包含任何额外的空格(如换行符)。

As suggested in the comments, you can avoid the danger of extra white space at the end of your script by omitting the ?>tag:

正如评论中所建议的,您可以通过省略?>标记来避免脚本末尾出现额外空白的危险:

<?php
$name = './img/ok.png';
$fp = fopen($name, 'rb');

header("Content-Type: image/png");
header("Content-Length: " . filesize($name));

fpassthru($fp);

You still need to carefully avoid white space at the top of the script. One particularly tricky form of white space is a UTF-8 BOM. To avoid that, make sure to save your script as "ANSI" (Notepad) or "ASCII" or "UTF-8 without signature" (Emacs) or similar.

您仍然需要小心避免脚本顶部的空白。一种特别棘手的空白形式是UTF-8 BOM。为避免这种情况,请确保将您的脚本另存为“ANSI”(记事本)或“ASCII”或“无签名的 UTF-8”(Emacs)或类似格式。

回答by ban-geoengineering

I feel like we can make this code a little bit easier by just getting the mime type from $image_info:

我觉得我们可以通过从 $image_info 获取 mime 类型来使这段代码更容易一些:

$file_out = "myDirectory/myImage.gif"; // The image to return

if (file_exists($file_out)) {

   $image_info = getimagesize($file_out);

   //Set the content-type header as appropriate
   header('Content-Type: ' . $image_info['mime']);

   //Set the content-length header
   header('Content-Length: ' . filesize($file_out));

   //Write the image bytes to the client
   readfile($file_out);
}
else { // Image file not found

    header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");

}

With this solution any type of image can be processed but it is just another option. Thanks ban-geoengineeringfor your contribution.

使用此解决方案可以处理任何类型的图像,但这只是另一种选择。感谢ban-geoengineering的贡献。

回答by Drew LeSueur

This should work. It may be slower.

这应该有效。它可能会更慢。

$img = imagecreatefromjpeg($filename);
header("Content-Type: image/jpg");
imagejpeg($img);
imagedestroy($img);

回答by Berk

I worked without Content-Length . maybe reason work for remote image files

我在没有 Content-Length 的情况下工作。也许是远程图像文件的原因

// open the file in a binary mode
$name = 'https://www.example.com/image_file.jpg';
$fp = fopen($name, 'rb');

// send the right headers
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: January 01, 2013'); // Date in the past
header('Pragma: no-cache');
header("Content-Type: image/jpg");
/* header("Content-Length: " . filesize($name)); */

// dump the picture and stop the script
fpassthru($fp);
exit;

回答by Joe Bubna

Another easy Option (not any better, just different) if you aren't reading from a database is to just use a function to output all the code for you... Note: If you also wanted php to read the image dimensions and give that to the client for faster rendering, you could easily do that too with this method.

如果您不从数据库中读取数据,另一个简单的选项(没有更好,只是不同)是仅使用函数为您输出所有代码... 注意:如果您还希望 php 读取图像尺寸并给出为了更快地呈现给客户端,您也可以使用此方法轻松做到这一点。

<?php
  Function insertImage( $fileName ) {
    echo '<img src="path/to/your/images/',$fileName,'">';    
  }
?>

<html>
  <body>
    This is my awesome website.<br>
    <?php insertImage( '1234.jpg' ); ?><br>
    Like my nice picture above?
  </body>
</html>