2011-08-26 72 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