2011-08-26 70 views
2

我有以下脚本将图像输出到浏览器,这很好。在Kohana 3.2视图中输出图像

$file_to_output=$_SERVER['DOCUMENT_ROOT'].'/static/imgs/uploads/20110318172207_16.jpg'; 
header('Content-Type: image/jpeg'); 
$raw=imagecreatefromjpeg($file_to_output); 

// Output the image 
imagejpeg($raw); 

// Free up memory 
imagedestroy($raw); 

,当我在一个视图中把这个完全相同的代码它不工作了,给一串字符STANGE像这样: JFIF> CREATOR:GD-JPEG V1.0 (使用IJG JPEG v62),默认质量 C

要使其在视图中工作,我需要做些什么?

+0

哪个版本的Kohana的是你使用? – Kemo

+0

我使用Kohana 3.2 – waterschaats

回答

5

你不应该把它放到视图中。所有视图输出都会被缓冲,稍后会通过Response对象返回。

这是所有响应的逻辑,所以你行动代码应该是这样的:

$path = DOCROOT.'static/imgs/uploads/20110318172207_16.jpg'; 

$this->response->headers('content-type',File::mime($path)) 
    ->body(file_get_contents($path)); 
+0

谢谢,所以我根本不使用视图?我仍然没有得到它的工作,它输出'图像损坏或截断'图像。但是文件102kb。 – waterschaats

+0

我工作!再次感谢。我在下一行'<?php defined('SYSPATH')或者die('没有直接脚本访问');' – waterschaats

3

另一种方法是:

$path = DOCROOT.'static/imgs/uploads/20110318172207_16.jpg'; 

// Send file as download 
$this->response->send_file($path); 

// Send file as inline 
$this->response->send_file($path, NULL, array('attachment' => 'inline')); 

// Another way to send as inline 
$this->response->body(file_get_contents($path)); 
$this->response->send_file(TRUE, $path); 

看到Response#send_file

+0

'的输出图像返回到浏览器,而不是发送它们作为下载 – Kemo

+0

有选项可以发送它们作为附件或内联使用这个'send_file'方法:) – SpadXIII

+0

当然,我在说你在这里粘贴的代码:) – Kemo