Validates the size of an uploaded image.

@param array|\Psr\Http\Message\UploadedFileInterface $file The uploaded file data from PHP.
@param array $options Options to validate width and height.
@return bool
@throws \InvalidArgumentException
489671
public static function imageSize($file, $options)
    {
        if (!isset($options['height']) && !isset($options['width'])) {
            throw new InvalidArgumentException('Invalid image size validation parameters! Missing `width` and / or `height`.');
        }

        $filename = static::getFilename($file);

        list($width, $height) = getimagesize($filename);

        $validHeight = $validWidth = null;

        if (isset($options['height'])) {
            $validHeight = self::comparison($height, $options['height'][0], $options['height'][1]);
        }
        if (isset($options['width'])) {
            $validWidth = self::comparison($width, $options['width'][0], $options['width'][1]);
        }
        if ($validHeight !== null && $validWidth !== null) {
            return ($validHeight && $validWidth);
        }
        if ($validHeight !== null) {
            return $validHeight;
        }
        if ($validWidth !== null) {
            return $validWidth;
        }

        throw new InvalidArgumentException('The 2nd argument is missing the `width` and / or `height` options.');
    }
347775
public function set($file)
    {
        //Resets `$error`
        unset($this->error);

        $this->file = (object)$file;

        //Errors messages
        $errors = [
            UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the maximum size that was specified in php.ini',
            UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the maximum size that was specified in the HTML form',
            UPLOAD_ERR_PARTIAL => 'The uploaded file was partially uploaded',
            UPLOAD_ERR_NO_FILE => 'No file was uploaded',
            UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder',
            UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
            UPLOAD_ERR_EXTENSION => 'File upload stopped by extension',
            'default' => 'Unknown upload error',
        ];

        //Checks errors during upload
        if (!isset($file['error']) || $file['error'] !== UPLOAD_ERR_OK) {
            //Gets the default error message, if the error can not be
            //  identified or if the key is not present
            if (!isset($file['error']) || !array_key_exists($file['error'], $errors)) {
                $file['error'] = 'default';
            }

            $this->setError($errors[$file['error']]);
        }

        return $this;
    }
1120751
protected function validateFileSize()
    {
        if (!is_numeric($this->max_file_size) && !is_int($this->max_file_size)) {
            // it is not set max file size limitation.
            return true;
        }

        if (is_array($this->files[$this->input_file_name]) && array_key_exists('size', $this->files[$this->input_file_name]) && $this->files[$this->input_file_name]['size'] > $this->max_file_size) {
            $this->setErrorMessage(
                sprintf(static::__('The uploaded file exceeds the max file size directive. (%s &gt; %s).'), $this->files[$this->input_file_name]['size'], $this->max_file_size),
                'RDU_1',
                $this->files[$this->input_file_name]['size'] . ' &gt; ' . $this->max_file_size,
                $this->files[$this->input_file_name]['name'],
                $this->files[$this->input_file_name]['size'],
                $this->files[$this->input_file_name]['type']
            );
            return false;
        } else {
            if (is_array($this->files[$this->input_file_name]) && array_key_exists('tmp_name', $this->files[$this->input_file_name]) && function_exists('filesize')) {
                if (filesize($this->files[$this->input_file_name]['tmp_name']) > $this->max_file_size) {
                    $this->setErrorMessage(
                        sprintf(static::__('The uploaded file exceeds the max file size directive. (%s &gt; %s).'), $this->files[$this->input_file_name]['size'], $this->max_file_size),
                        'RDU_1',
                        $this->files[$this->input_file_name]['size'] . ' &gt; ' . $this->max_file_size,
                        $this->files[$this->input_file_name]['name'],
                        $this->files[$this->input_file_name]['size'],
                        $this->files[$this->input_file_name]['type']
                    );
                    return false;
                }
            }
        }

        return true;
    }
23633
protected function validate(UploadFile $file)
    {
        if (parent::validate($file)) {

            $info = getimagesize($file->getFileTemp());
            $width = $info[ 0 ];
            $height = $info[ 1 ];

            /* Validate width min size */
            if ($this->allowedImageSize[ 'width' ][ 'min' ] > 0) {
                if ($width < $this->allowedImageSize[ 'width' ][ 'min' ]) {
                    $this->errors[] = language()->getLine(
                        'IMAGE_E_ALLOWED_MIN_WIDTH_SIZE',
                        [$this->allowedFileSize[ 'min' ], $width]
                    );
                }
            }

            /* Validate width max size */
            if ($this->allowedImageSize[ 'width' ][ 'max' ] > 0) {
                if ($width > $this->allowedImageSize[ 'width' ][ 'max' ]) {
                    $this->errors[] = language()->getLine(
                        'IMAGE_E_ALLOWED_MAX_WIDTH_SIZE',
                        [$this->allowedFileSize[ 'max' ], $width]
                    );
                }
            }

            /* Validate height min size */
            if ($this->allowedImageSize[ 'height' ][ 'min' ] > 0) {
                if ($height < $this->allowedImageSize[ 'width' ][ 'min' ]) {
                    $this->errors[] = language()->getLine(
                        'IMAGE_E_ALLOWED_MIN_HEIGHT_SIZE',
                        [$this->allowedFileSize[ 'min' ], $height]
                    );
                }
            }

            /* Validate height max size */
            if ($this->allowedImageSize[ 'height' ][ 'max' ] > 0) {
                if ($height > $this->allowedImageSize[ 'width' ][ 'max' ]) {
                    $this->errors[] = language()->getLine(
                        'IMAGE_E_ALLOWED_MAX_HEIGHT_SIZE',
                        [$this->allowedFileSize[ 'max' ], $height]
                    );
                }
            }
        }

        if (count($this->errors) == 0) {
            return true;
        }

        return false;
    }
1162008
public function validate($file, Constraint $constraint)
    {
        if (!in_array($file->getMimeType(), $this->mimeTypes)) {
            $this->context->buildViolation($constraint->messageMimeTypes)
                ->atPath('file')
                ->addViolation();
        }
        if ($file->getSize() > $file->getMaxFilesize()) {
            $this->context->buildViolation($constraint->messageMaxSize, array('%max_size%' => $file->getMaxFilesize()))
                ->atPath('file')
                ->addViolation();
        }
    }
948331
private function validateLocalFile($path) {
        if (!is_file($path)) {
            throw new InvalidArgumentException('File does not exist: ' . $path);
        }

        if (!filesize($path)) {
            throw new InvalidArgumentException('File is of zero length: ' . $path);
        }
    }
888853
private function moveAndCreatePhoto(
        UploadedFile $file,
        $size = ['l' => [1000, 1000], 's' => [300, 300]]
    ) {
        $extension = '.' . $file->extension();

        $name = token();
        $filename = $name . $extension;

        $path = upload_path_images();
        $imageTmp = Image::make($file->getRealPath());

        if (!$imageTmp) {
            return false;
        }

        $largeSize = $size['l'];
        $thumbSize = $size['s'];

        // save original
        $imageTmp->save($path . $name . ImageThumb::$originalAppend . $extension);

        // if width is the biggest - resize on max width
        if ($imageTmp->width() > $imageTmp->height()) {
            // resize the image to the large height and constrain aspect ratio (auto width)
            $imageTmp->resize(null, $largeSize[1], function ($constraint) {
                $constraint->aspectRatio();
            })->save($path . $filename);

            // resize the image to the thumb height and constrain aspect ratio (auto width)
            $imageTmp->resize(null, $thumbSize[1], function ($constraint) {
                $constraint->aspectRatio();
            })->save($path . $name . ImageThumb::$thumbAppend . $extension);
        }
        else {
            // resize the image to the large width and constrain aspect ratio (auto height)
            $imageTmp->resize($largeSize[0], null, function ($constraint) {
                $constraint->aspectRatio();
            })->save($path . $filename);

            // resize the image to the thumb width and constrain aspect ratio (auto width)
            $imageTmp->resize($thumbSize[0], null, function ($constraint) {
                $constraint->aspectRatio();
            })->save($path . $name . ImageThumb::$thumbAppend . $extension);
        }

        return $filename;
    }
653522
function load(ImageInterface $image, array $options = [])
    {
        list($width, $height) = $options['size'];

        $filter = new SmartResize(new Box($width, $height));
        $image = $filter->apply($image);

        return $image;
    }
109963
private function validateError(UploadedFile $uploadedFile) {
        switch($uploadedFile->getError()) {
            case UPLOAD_ERR_OK:
                //Do Nothing
                break;
            case UPLOAD_ERR_INI_SIZE:
                throw new Exception('File too large, must not be greater than ' . ini_get('upload_max_filesize'), 401);
                break;
            case UPLOAD_ERR_NO_FILE:
                throw new Exception('No File Uploaded', 401);
                break;
            default:
                throw new Exception($uploadedFile->getError(), 401);
                break;
        }
    }
281526
public function getImageSize($file, $type = '')
	{
		// Reset values
		$this->resetValues();

		// Treat image type as unknown if extension or mime type is unknown
		if (!preg_match('/\.([a-z0-9]+)$/i', $file, $match) && empty($type))
		{
			$this->getImagesizeUnknownType($file);
		}
		else
		{
			$extension = (empty($type) && isset($match[1])) ? $match[1] : preg_replace('/.+\/([a-z0-9-.]+)$/i', '$1', $type);

			$this->getImageSizeByExtension($file, $extension);
		}

		return sizeof($this->size) > 1 ? $this->size : false;
	}
254837
private function setSize($size): void
    {
        if (false === is_int($size)) {
            throw new \InvalidArgumentException('Upload file size must be an integer');
        }

        $this->size = $size;
    }
1333565
public function setFile($file)
    {
        if (empty($file) || false === stream_resolve_include_path($file)) {
            throw new Exception\InvalidArgumentException('Invalid options to validator provided');
        }

        $this->options['file'] = $file;
        return $this;
    }
768189
protected function validateOptions(array $options, $method)
    {
        $options = parent::validateOptions($options, $method);

        $options = $this->setOptionIfNotSet($options, 'width', 0);
        $options = $this->setOptionIfNotSet($options, 'height', 0);

        $this->checkIfInteger($options, 'width', __METHOD__);
        $this->checkIfInteger($options, 'height', __METHOD__);

        return $options;
    }
1350419
public function validateFile(Entity\File $file, $sourceFilePath = null)
	{
		if ( ! $file instanceof Entity\Image) {
			return;
		}

		if (is_null($sourceFilePath)) {
			return;
		}

		$info = new ImageInfo($sourceFilePath);
		if($info->hasError()) {
			throw new Exception\RuntimeException($info->getError());
		}

		// Assumes memory_limit is in MB
		// "-1" means no limit
		$memoryLimit = (int) ini_get('memory_limit');
		if ($memoryLimit < 0) {
			return;
		}
		
		$memoryLeft = (int) $memoryLimit * 1024 * 1024 - memory_get_usage(); // Should use real usage or not?
		// Read data from image info, default bitsPerChannel to 8, channel count to 4
		$memoryRequired = ($info->getWidth() * $info->getHeight() * ($info->getBits() ?: 8) * ($info->getChannels() ?: 4)) * 2;

		if ($memoryRequired > $memoryLeft) {
			$message = "Not enough memory [{$memoryLeft} bytes] to resize the image, required amount [{$memoryRequired} bytes]";

			throw new Exception\InsufficientSystemResources(self::EXCEPTION_MESSAGE_KEY, $message);
		}
	}
745431
public function isValidSize()
    {
        // If file was blocked via PHP for being excessive size, shortcut here
        switch ($this->tmpFile['error']) {
            case UPLOAD_ERR_INI_SIZE:
            case UPLOAD_ERR_FORM_SIZE:
                return false;
        }
        $maxSize = $this->getAllowedMaxFileSize($this->getFileExtension());
        return (!$this->tmpFile['size'] || !$maxSize || (int)$this->tmpFile['size'] < $maxSize);
    }
1079953
static protected function validateUploadedFileContents(
        Column $column,
        FileConfigInterface $fileConfig,
        SymfonyUploadedFile $file,
        $fileIndex,
        array &$errors
    ) {
        $localizations = $column::getValidationErrorsMessages();
        $filesGroupName = $fileConfig->getName();
        $errorsKey = $filesGroupName . '.' . $fileIndex;

        $mimeType = $file->getMimeType() ?: $file->getClientMimeType();
        if (!in_array($mimeType, $fileConfig->getAllowedMimeTypes(), true)) {
            $errors[$errorsKey][] = sprintf(
                RecordValueHelpers::getErrorMessage(
                    $localizations,
                    $column->isItAnImage() ? $column::IMAGE_TYPE_IS_NOT_ALLOWED : $column::FILE_TYPE_IS_NOT_ALLOWED
                ),
                $mimeType,
                $filesGroupName,
                implode(', ', $fileConfig->getAllowedMimeTypes())
            );
        } else if ($file->getSize() / 1024 > $fileConfig->getMaxFileSize()) {
            $errors[$errorsKey][] = sprintf(
                RecordValueHelpers::getErrorMessage($localizations, $column::FILE_SIZE_IS_TOO_LARGE),
                $filesGroupName,
                $fileConfig->getMaxFileSize()
            );
        }
        return !empty($errors[$errorsKey]);
    }
585116
public function size(String $fileName) : stdClass
    {
        if( $this->mime->type($fileName, 0) === 'image' )
        {
            $data = getimagesize($fileName);
        }
        elseif( is_string($fileName) )
        {
            $data = getimagesizefromstring($fileName);
        }
        else
        {
            throw new InvalidArgumentException(NULL, '[file]');
        }

        return (object)
        [
            'width'     => $data[0],
            'height'    => $data[1],
            'extension' => $this->extension($data[2]),
            'img'       => $data[3],
            'bits'      => $data['bits'],
            'mime'      => $data['mime']
        ];
    }