0

我将图像存储在redis中。

$image = $cache->remember($key, null, function () use ($request, $args) {
            $image = $this->get('image');
            $storage = $this->get('storage');

            return $image->load($storage->get($args['path'])->read())
                        ->withFilters($request->getQueryParams())
                        ->stream();
        });

并试图取回它:

return (new Response())
                ->withHeader('Content-Type', 'image/png')
                ->withBody($image);

它给了我这个错误:

Return value of Slim\Handlers\Strategies\RequestResponse::__invoke() 
must implement interface Psr\Http\Message\ResponseInterface, string returned

$image变量是该图像的字节。如何将这些字节转换为流?

4

1 回答 1

1

为了从字符串创建流,您可以使用 Slim 的实现Psr\Http\Message\StreamFactoryInterface(参见PSR-17:HTTP 工厂,或任何其他实现相同接口的外部库(如laminas-dictoros)。

使用 Slim 库,它应该是这样的:

<?php

use Slim\Psr7\Response;
use Slim\Psr7\Factory\StreamFactory;

// The string to create a stream from.
$image = $cache->remember($key, null, function () use ($request, $args) {
    //...
});

// Create the stream factory.
$streamFactory = new StreamFactory();

// Create a stream from the provided string.
$stream = $streamFactory->createStream($image);

// Create a response.
$response = (new Response())
                ->withHeader('Content-Type', 'image/png')
                ->withBody($stream);

// Do whatever with the response.

或者,您可以使用以下方法StreamFactory::createStreamFromFile

<?php

// ...

/*
 * Create a stream with read-write access:
 *
 *  'r+': Open for reading and writing; place the file pointer at the beginning of the file.
 *  'b': Force to binary mode.
 */
$stream = $streamFactory->createStreamFromFile('php://temp', 'r+b');

// Write the string to the stream.
$stream->write($image);

// ...
于 2020-04-11T21:51:27.457 回答