如何从Redis缓存创建新流

问题描述 投票:0回答:1

我正在将图像存储在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变量是该图像的字节。如何将这些字节转换为流?

php slim psr-4 slim-4
1个回答
0
投票

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

使用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);

// ...
© www.soinside.com 2019 - 2024. All rights reserved.