2016-07-06 62 views
1

我想從SLIM控制器顯示動態生成的圖像,但我得到一個空白屏幕。 謝謝。PHP SLIM:如何返回動態生成的圖像

public function textToImage($request, $response, $args) { 

    // The text to draw 
    $text = "Hello World"; 
    $length=strlen($text); 
    // Create the image 

    $im = imagecreatetruecolor($length*12, 30); 

    // Create some colors 
    $white = imagecolorallocate($im, 255, 255, 255); 
    $grey = imagecolorallocate($im, 128, 128, 128); 
    $black = imagecolorallocate($im, 44, 62, 80); 
    $boxcolor=imagecolorallocate($im, 95, 128, 149); 

    $font = 'Helvetica.ttf'; 
    imagefilledrectangle($im, 0, 0, $length*9+$capitaladjust, 29, $white); 
    imagettftext($im, 13, 0, 0, 20, $black, $font, $text); 

    $response->getBody()->write(base64_encode($im)); 
    $response = $response->withHeader('Content-type', 'image/png');  
    return $response; 
} 

回答

4

base64編碼$im不會創建有效的PNG文件。嘗試使用imgpng,然後發送它創建的PNG文件的原始內容。

的代碼會是這個樣子:

ob_start(); 
imagepng($im); 
$data = ob_get_contents(); 
ob_end_clean(); 

$response->getBody()->write($data); 
$response = $response->withHeader('Content-type', 'image/png');  
return $response;