Silex无法将图像显示为响应

时间:2016-07-09 10:46:22

标签: php silex

我无法将任何响应显示为图像。我尝试过silex方法和纯PHP,就像这样

   $file = '1465797900_yoda.png';


    if (!file_exists('images/'.$file)) {
    return $app->abort(404, 'The image was not found.');
}

$stream = function () use ($file) {
    readfile($file);
};

return $app->stream($stream, 200, array('Content-Type' => 'image/png'));

或纯PHP:

   $file = 'images/1465797900_yoda.png';
$type = 'image/png';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
echo readfile($file); 

如果我使用方法1,我的响应是空白图像,但方法2返回随机轨道,如下所示:

J j ? 'T|֢1 Kc Zu # 9 G < !4# D xU _PW Fܽ ! rŨ% Gs u6 ?0 _ o。>IEND B`

Pure PHP没有问题,只有Silex。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

我已经写了以下文件来从一个文件夹中提供Pics:

public function getpic( $id ) {
    $path = '/assets/userpics/' . $id;
    if ( is_file( $path ) ) {
        return new BinaryFileResponse( $path );
    }
    //make some error stuff
}

在您调用图像的Html中使用或通过js

加载它