diff --git a/src/Intervention/Image/AbstractDecoder.php b/src/Intervention/Image/AbstractDecoder.php index 00cd4f43..ac93cf0b 100644 --- a/src/Intervention/Image/AbstractDecoder.php +++ b/src/Intervention/Image/AbstractDecoder.php @@ -2,6 +2,9 @@ namespace Intervention\Image; +use GuzzleHttp\Psr7\Stream; +use Psr\Http\Message\StreamInterface; + abstract class AbstractDecoder { /** @@ -85,22 +88,35 @@ abstract class AbstractDecoder /** * Init from given stream * - * @param $stream + * @param StreamInterface|resource $stream * @return \Intervention\Image\Image */ public function initFromStream($stream) { - $offset = ftell($stream); - $shouldAndCanSeek = $offset !== 0 && $this->isStreamSeekable($stream); - - if ($shouldAndCanSeek) { - rewind($stream); + if (!$stream instanceof StreamInterface) { + $stream = new Stream($stream); } - $data = @stream_get_contents($stream); + try { + $offset = $stream->tell(); + } catch (\RuntimeException $e) { + $offset = 0; + } + + $shouldAndCanSeek = $offset !== 0 && $stream->isSeekable(); if ($shouldAndCanSeek) { - fseek($stream, $offset); + $stream->rewind(); + } + + try { + $data = $stream->getContents(); + } catch (\RuntimeException $e) { + $data = null; + } + + if ($shouldAndCanSeek) { + $stream->seek($offset); } if ($data) { @@ -112,18 +128,6 @@ abstract class AbstractDecoder ); } - /** - * Checks if we can move the pointer for this stream - * - * @param resource $stream - * @return bool - */ - private function isStreamSeekable($stream) - { - $metadata = stream_get_meta_data($stream); - return $metadata['seekable']; - } - /** * Determines if current source data is GD resource * @@ -213,6 +217,7 @@ abstract class AbstractDecoder */ public function isStream() { + if ($this->data instanceof StreamInterface) return true; if (!is_resource($this->data)) return false; if (get_resource_type($this->data) !== 'stream') return false; diff --git a/tests/AbstractDecoderTest.php b/tests/AbstractDecoderTest.php index 4d633ce2..7db29f33 100644 --- a/tests/AbstractDecoderTest.php +++ b/tests/AbstractDecoderTest.php @@ -61,6 +61,9 @@ class AbstractDecoderTest extends PHPUnit_Framework_TestCase $source = $this->getTestDecoder(fopen(__DIR__ . '/images/test.jpg', 'r')); $this->assertTrue($source->isStream()); + $source = $this->getTestDecoder(new \GuzzleHttp\Psr7\Stream(fopen(__DIR__ . '/images/test.jpg', 'r'))); + $this->assertTrue($source->isStream()); + $source = $this->getTestDecoder(null); $this->assertFalse($source->isStream()); }