lost111in
lost111in

Reputation: 207

PHP SLIM : How to return dynamically generated images

I am trying to display a dynamically generated image from SLIM controller but I am getting a blank screen. Thanks.

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;
 }

Upvotes: 1

Views: 1007

Answers (1)

Rob Allen
Rob Allen

Reputation: 12778

base64 encoding $im will not create a valid PNG file. Try using imgpng and then sending the raw contents of the PNG file that it creates.

The code would look something like this:

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

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

Upvotes: 5

Related Questions