Silex / Symfony响应无法正确返回图像数据

时间:2017-07-18 06:53:19

标签: php symfony silex

我希望用PHP请求的用户大小显示Image。

工作代码。没有框架。

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

?>

此代码正确显示图像。这是输出预览。

Correct Output

不工作代码。使用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;
});

此代码显示损坏的图像。这是输出预览。

Incorrect output

这是标题。

  

缓存控制:无缓存,私有   连接:保持活跃   内容处置:内联   Content-Type:image / png日期:星期二,2017年7月18日06:15:56 GMT   服务器:Apache   传输编码:分块   通过:1.1 vegur

我想我接近答案,但有&#39;&lt;&#39;首先输出错误。我无法正确删除substr。

我真的遇到了麻烦。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

size不是GET / POST参数。你应该从$request

得到它
$size = $request->get('size');

或来自函数参数

$app->get('/resize/{size}', function (Symfony\Component\HttpFoundation\Request $request, $size) use ($app) {
    // $size = $_REQUEST['size']; // remove this

同样Symfony\Component\HttpFoundation\BinaryFileResponse用于二进制(文件)响应。

$path = sys_get_temp_dir() . '/qwerty';
imagepng($out, $path, 9);
$response = new \Symfony\Component\HttpFoundation\BinaryFileResponse($path, 200, array('Content-Type'=>'image/png'), false, 'inline');
return $response;

答案 1 :(得分:0)

检查为silex编写的php文件,在其中一个文件的开头可能会有一个额外的<,这会导致此问题。