在codeigniter中使用readfile()从控制器显示图像


Display an image using readfile() from controller in codeigniter

为了测试readfile(),我将以下代码放在主index.php文件的最顶部,图像正确显示。然而,当我把完全相同的代码在我的控制器,它只是显示一个破碎的图像。

我试着用"$this->output->set_header('Content-Type: image/jpeg');"替换标题行,但只是得到了混乱的字符。我怎么能让它从控制器显示,因为它从索引文件?我难住了。

代码:

$file = '/home/www/noname.com/public/captcha/1444721011.7843.jpg';
 header('Content-Type: image/jpeg');
readfile($file);
exit;

我试着把"header_remove();"在控制器前的代码。结果仍然只是一个破碎的图像(尽管标题看起来相同)。这样的:

HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Length: 2166
Content-Type: image/jpeg
Date: Tue, 13 Oct 2015 12:27:43 GMT
Keep-Alive: timeout=5, max=100
Server: Apache

任何想法吗?

编辑:我确实注意到在我所有的页面<之前有一个空行!DOCTYPE>. 在这个链接的顶部可以看到一个例子,它也是一个编码器网站。查看源代码:call2you。有限公司我在想这是不是原因。知道这条线是怎么来的吗,我可以把它去掉?

我认为如果您删除exit调用,您的示例应该在控制器中正常工作。

如果你真的想中止脚本的执行,那么你的方法应该是这样的:

public function display_image () {
    $file = '/home/www/noname.com/public/captcha/1444721011.7843.jpg';
    $contents = file_get_contents($file);
    $this->output
            ->set_status_header(200)
            ->set_content_type('image/jpeg')
            ->set_output($contents)
            ->_display();
    exit;
}

应该允许干净的退出

我在这里回答我自己的问题。问题是在源代码的顶部神秘地添加了空行。查找这一行的源代码变得太耗时了,所以我的解决方案是将ob_end_clean();在页眉之前。所以:

     $file = '/home/www/noname.com/public/captcha/1444721011.7843.jpg';
     ob_end_clean();
     $this->output->set_header('Content-Type: image/jpeg');
     readfile($file);

谢谢你,那些回应。