2017-02-23 76 views
1

嗨我使用php的gd庫來生成圖像。我已經決定將它融入到laravel中,並且我設法讓它工作。Laravel生成圖像並添加內容類型標題

我的問題是,如果laravel有時會覆蓋我的內容類型標題。

這是我的控制器:

public function imga($algorythm,$w=false,$h=false){ 
    if (!$w) $w=rand(250,750); 
    if (!$h) $h=rand(250,750); 
    $im = imagecreatetruecolor($w, $h); 

    //Here some fancy function is called 
    if (method_exists($this,'img_'.$algorythm)){ 
     $this->{'img_'.$algorythm}($im,$w,$h); 
    } 

    header("Content-type: image/png"); 
    imagepng($im); 
    imagedestroy($im); 
} 

大部分的時間,如果圖像是足夠大的瀏覽器只顯示它不如預期,但如果圖片太小laravel覆蓋內容類型標題以「文本/ html; charset = UTF-8「。

我讀過https://laravel.com/docs/5.4/responses,但爲了讓它這樣我需要一個字符串。

所以我看過這個:PHP: create image with ImagePng and convert with base64_encode in a single file?但我不確定這是否正確的方式,它看起來像一個骯髒的黑客給我。

我應該把imagepng調用放入一個視圖並在那裏添加標題,這不是有點矯枉過正嗎?

如何使用輸出數據而不是在laravel中返回的函數。

回答

2

Laravel控制器的操作通常會給出某種響應,默認爲text/html

你修復可能是那麼容易,因爲:

header("Content-Type: image/png"); 
    imagepng($im); 
    imagedestroy($im); 
    exit; 
} 

或者您可以使用一個包狀的干預(http://image.intervention.io)。從中可以生成圖像響應。

+0

你的意思是我只需要在末尾添加退出? – Falk

+0

是的,它會停止執行,所以沒有更多的標題或其他內容將被添加到輸出,圖像將顯示原樣。 – Robert

+0

太棒了! – Falk

1

一種方法是捕捉圖像輸出與​​然後進行與響應:

public function imga($algorythm,$w=false,$h=false){ 
    if (!$w) $w=rand(250,750); 
    if (!$h) $h=rand(250,750); 
    $im = imagecreatetruecolor($w, $h); 

    //Here some fancy function is called 
    if (method_exists($this,'img_'.$algorythm)){ 
     $this->{'img_'.$algorythm}($im,$w,$h); 
    } 


    ob_start(); 
    $rendered_buffer = imagepng($im); 
    $buffer = ob_get_contents(); 
    imagedestroy($im); 
    ob_end_clean(); 

    $response = Response::make($rendered_buffer); 
    $response->header('Content-Type', 'image/png'); 
    return $response; 
} 

編輯:剛剛看到你的鏈接,這基本上只是一個實現。

如果你想要一個「更laravel」的方式,你可以保存圖像,返回它,然後將其刪除:

public function imga($algorythm,$w=false,$h=false){ 
    if (!$w) $w=rand(250,750); 
    if (!$h) $h=rand(250,750); 
    $im = imagecreatetruecolor($w, $h); 

    //Here some fancy function is called 
    if (method_exists($this,'img_'.$algorythm)){ 
     $this->{'img_'.$algorythm}($im,$w,$h); 
    } 

    // store the image 
    $filepath = storage_path('tmpimg/' . uniqid() . '.png'); 
    imagepng($im, $filepath); 
    imagedestroy($im); 

    $headers = array(
     'Content-Type' => 'image/png' 
    ); 

    // respond with the image then delete it 
    return response()->file($filepath, $headers)->deleteFileAfterSend(true); 
} 
+0

太棒了,工作正常! – Falk