Silex/Symfony 响应 returns 图像数据不正确

Silex/Symfony Response doesn't returns image data correctly

我想显示用户使用 PHP 请求的尺寸的图像。

工作代码。没有框架。

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

这是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

我想我接近答案了,但是在错误输出的开头有'<'。我无法正确删除 substr。

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

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;

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