Search code examples
phpsymfonysilex

Silex/Symfony Response doesn't returns image data correctly


I want to show Image with the size user requested with PHP.

Working code. No framework.

<?php

require_once __DIR__ . '/vendor/autoload.php';

define('BASE_SIZE', 1000);

$original = imagecreatefrompng('image.png');

$size = $_REQUEST['size'];
if($size == BASE_SIZE) {
  $out = $original;
}
else {
  $out = imagecreatetruecolor($size ,$size);
  imagecopyresampled($out, $original, 0, 0, 0, 0, $size, $size, BASE_SIZE, BASE_SIZE);
}

ob_start();
imagepng($out, null, 9);
$content = ob_get_contents();
ob_end_clean();

header('Content-type: image/png');
echo $content;

?>

This code shows image correctly. And Here is output preview.

Correct Output

Not Working code. Using Silex.

$app->get('/resize/{size}', function (Symfony\Component\HttpFoundation\Request $request, $size) use ($app) {

    define('BASE_SIZE', 1000);

    $original = imagecreatefrompng('image.png');

    if($size == BASE_SIZE) {
      $out = $original;
    }
    else {
      $out = imagecreatetruecolor($size ,$size);
      imagecopyresampled($out, $original, 0, 0, 0, 0, $size, $size, BASE_SIZE, BASE_SIZE);
    }

    ob_start();
    imagepng($out, null, 9);
    $content = ob_get_contents();
    ob_end_clean();

    $response = new Symfony\Component\HttpFoundation\Response($content, 200);
    $response->headers->set('Content-Type', 'image/png');
    $response->headers->set('Content-Disposition', 'inline');
    return $response;
});

This code shows broken image. And Here is output preview.

Incorrect output

And this is header.

Cache-Control:no-cache, private Connection:keep-alive Content-Disposition:inline Content-Type:image/png Date:Tue, 18 Jul 2017 06:15:56 GMT Server:Apache Transfer-Encoding:chunked Via:1.1 vegur

I think I'm near to the answer, But there is '<' at first of incorrect output. I couldn't remove with substr correctly.

I'm really in trouble. Any Idea?


Solution

  • Check your php files written for silex, there may be an extra < at the beginning of one of those, that causes this problem.