Neos\Media\Domain\Service\ImageService::getImageSize PHP Method

getImageSize() public method

Get the size of a Flow PersistentResource that contains an image file.
public getImageSize ( PersistentResource $resource ) : array
$resource Neos\Flow\ResourceManagement\PersistentResource
return array width and height as keys
    public function getImageSize(PersistentResource $resource)
    {
        $cacheIdentifier = $resource->getCacheEntryIdentifier();
        $imageSize = $this->imageSizeCache->get($cacheIdentifier);
        if ($imageSize !== false) {
            return $imageSize;
        }
        // TODO: Special handling for SVG should be refactored at a later point.
        if ($resource->getMediaType() === 'image/svg+xml') {
            $imageSize = ['width' => null, 'height' => null];
        } else {
            try {
                $imagineImage = $this->imagineService->read($resource->getStream());
                $sizeBox = $imagineImage->getSize();
                $imageSize = array('width' => $sizeBox->getWidth(), 'height' => $sizeBox->getHeight());
            } catch (\Exception $e) {
                throw new ImageFileException(sprintf('The given resource was not an image file your choosen driver can open. The original error was: %s', $e->getMessage()), 1336662898);
            }
        }
        $this->imageSizeCache->set($cacheIdentifier, $imageSize);
        return $imageSize;
    }

Usage Example

 /**
  * Calculates and sets the width and height of this Image asset based
  * on the given PersistentResource.
  *
  * @param PersistentResource $resource
  * @return void
  * @throws ImageFileException
  */
 protected function calculateDimensionsFromResource(PersistentResource $resource)
 {
     try {
         $imageSize = $this->imageService->getImageSize($resource);
     } catch (ImageFileException $imageFileException) {
         throw new ImageFileException(sprintf('Tried to refresh the dimensions and meta data of Image asset "%s" but the file of resource "%s" does not exist or is not a valid image.', $this->getTitle(), $resource->getSha1()), 1381141468, $imageFileException);
     }
     $this->width = is_int($imageSize['width']) ? $imageSize['width'] : null;
     $this->height = is_int($imageSize['height']) ? $imageSize['height'] : null;
 }