@param \Imagick $image
@param array    $size
@param bool     $needExactSize

@return \Imagick

@throws \ImagickException
969356
private function setImageSize($image, $size, $needExactSize = false)
    {
        if (empty($size)) {
            return $image;
        }

        if ($needExactSize || $image->getImageWidth() > $size[0]) {
            if ($size[0] == 0 || $size[1] == 0) {
                $image->scaleImage($size[0], $size[1]);
            } else {
                $image->cropThumbnailImage($size[0], $size[1]);
            }
        }

        return $image;
    }
1366096
private function ensureMinimumImageSize(Image $mainImage): ?Image {
        if ($mainImage->getWidth() >= $this->config()->get('image_min_width')
          && $mainImage->getHeight() >= $this->config()->get('image_min_height')) {
            return $mainImage;
        }

        return null;
    }
1333353
protected function addFileRule($attribute, $size, $mimes, $count = 1, $isRequired = false)
    {
        if ($this->has($attribute) && is_string($this->$attribute)) {
            $this->rules[$attribute] = "elfinder_max:{$size}|elfinder:{$mimes}";
        } else  if ($this->file($attribute) && is_array($this->$attribute)){
            $this->rules[$attribute] = "array|max:{$count}";
            foreach($this->file($attribute) as $key => $file) {
                if(array_search($key, ['x','y','width','height']) !== false) {
                    continue;
                }

                $this->rules[$attribute . '.' . $key] = "max:{$size}|image|mimes:{$mimes}";
                if ($isRequired) {
                    $this->rules[$attribute . '.' . $key] = "required|{$this->rules[$attribute . '.' . $key]}";
                }
            }
        } else if ($this->has($attribute) && is_array($this->$attribute)) {
            $this->rules[$attribute] = "array|max:{$count}";
            foreach($this->get($attribute) as $key => $file) {
                if(array_search($key, ['x','y','width','height']) !== false) {
                    continue;
                }

                $this->rules[$attribute . '.' . $key] = "elfinder_max:{$size}|elfinder:{$mimes}";
                if ($isRequired) {
                    $this->rules[$attribute . '.' . $key] = "required|{$this->rules[$attribute . '.' . $key]}";
                }
            }
        } else if ($this->file($attribute)) {
            $this->rules[$attribute] = "max:{$size}|image|mimes:{$mimes}";
        }

        if ($isRequired) {
            $this->rules[$attribute] = "required|{$this->rules[$attribute]}";
        }
    }
479769
static function createImage( $width, $height, &$useTruecolor )
    {
        if ( $useTruecolor === null )
        {
//             print( "has GD2='" . eZImageInterface::hasGD2() . "'<br/>" );
            $useTruecolor = eZImageInterface::hasGD2();
        }
        if ( $useTruecolor and
             !function_exists( 'ImageCreateTrueColor' ) )
        {
            eZDebug::writeWarning( 'Function ImageCreateTrueColor does not exist, cannot create true color images', __METHOD__ );
            $useTruecolor = false;
        }
        if ( $useTruecolor )
            $imageObject = ImageCreateTrueColor( $width, $height );
        else
            $imageObject = ImageCreate( $width, $height );
        return $imageObject;
    }
734171
function scaleImageExact( $imageObject, $filterData, &$filterVariables, $sourceMimeData, $destinationMimeData )
    {
        return $this->scaleImageCopy( $imageObject,
                                      $this->createGeometry( $filterData['data'][0], $filterData['data'][1] ),
                                      $sourceMimeData, $destinationMimeData );
    }
397061
protected function checkSize($imagick)
    {
        $width = $imagick->getImageWidth();
        if ($width > self::MAX_RECOMMENDED_IMAGE_WIDTH) {
            $this->logger->warning(sprintf(
                _('画像の幅は %1$s 以下にすべきです。「%2$s」の幅は %3$s です。'),
                self::MAX_RECOMMENDED_IMAGE_WIDTH . 'px',
                $this->filename,
                $width . 'px'
            ));
        }

        $height = $imagick->getImageHeight();
        if ($height > self::MAX_RECOMMENDED_IMAGE_HEIGHT) {
            $this->logger->warning(sprintf(
                _('画像の高さは %1$s 以下にすべきです。「%2$s」の高さは %3$s です。'),
                self::MAX_RECOMMENDED_IMAGE_HEIGHT . 'px',
                $this->filename,
                $height . 'px'
            ));
        }
    }
72335
protected function getHighestEnergyPoint(\Imagick $image)
    {
        $size = $image->getImageGeometry();
        // It's more performant doing random pixel uplook via GD
        $im = imagecreatefromstring($image->getImageBlob());
        if ($im === false) {
            $msg = 'GD failed to create image from string';
            throw new \Exception($msg);
        }
        $xcenter = 0;
        $ycenter = 0;
        $sum = 0;
        // Only sample 1/50 of all the pixels in the image
        $sampleSize = round($size['height']*$size['width'])/50;

        for ($k=0; $k<$sampleSize; $k++) {
            $i = mt_rand(0, $size['width']-1);
            $j = mt_rand(0, $size['height']-1);

            $rgb = imagecolorat($im, $i, $j);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;

            $val = $this->rgb2bw($r, $g, $b);
            $sum += $val;
            $xcenter += ($i+1)*$val;
            $ycenter += ($j+1)*$val;
        }

        if ($sum) {
            $xcenter /= $sum;
            $ycenter /= $sum;
        }

        $point = array('x' => $xcenter, 'y' => $ycenter, 'sum' => $sum/round($size['height']*$size['width']));

        return $point;
    }
367661
public function applyToImage(ImagineImageInterface $image): ImagineImageInterface
    {
        $desiredAspectRatio = $this->getAspectRatio();
        if ($desiredAspectRatio !== null) {
            $originalWidth = $image->getSize()->getWidth();
            $originalHeight = $image->getSize()->getHeight();

            [$newX, $newY, $newWidth, $newHeight] = self::calculateDimensionsByAspectRatio($originalWidth, $originalHeight, $desiredAspectRatio);

            $point = new Point($newX, $newY);
            $box = new Box($newWidth, $newHeight);
        } else {
            $point = new Point($this->x, $this->y);
            $box = new Box($this->width, $this->height);
        }
        return $image->crop($point, $box);
    }
1048139
private function _resize (ImageInterface $image, BoxInterface $newSize)
		{
			$size = $image->getSize();
			$ratio = min($newSize->getHeight() / $size->getHeight(), $newSize->getWidth() / $size->getWidth());
			if ($ratio < 1)
				$image->resize($size->scale($ratio));
		}
836149
public function execute($image)
    {
        $backupName = $this->argument(0)->value();

        $backup = $image->getBackup($backupName);

        if ($backup instanceof \Imagick) {

            // destroy current core
            $image->getCore()->clear();

            // clone backup
            $backup = clone $backup;

            // reset to new resource
            $image->setCore($backup);

            return true;
        }

        throw new \Hail\Image\Exception\RuntimeException(
            "Backup not available. Call backup({$backupName}) before reset()."
        );
    }
473638
public static BufferedImage scaleImage( BufferedImage image, int newSize ) throws Exception {

        int imageWidth = image.getWidth();
        int imageHeight = image.getHeight();
        int width;
        int height;
        if (imageWidth > imageHeight) {
            width = newSize;
            height = imageHeight * width / imageWidth;
        } else {
            height = newSize;
            width = height * imageWidth / imageHeight;
        }

        BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(image, 0, 0, width, height, null);
        g.dispose();

        return resizedImage;
    }
404140
public static byte[] scaleImage(byte[] imageBytes, String outputFormat,
                                    Integer targetSize) throws Exception {

        InputStream is = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] imageInBytes = null;
        BufferedImage image = null;
        BufferedImage resizedImage = null;

        try {
            is = new ByteArrayInputStream(imageBytes);
            image = ImageIO.read(is);
            resizedImage = Scalr.resize(image, targetSize);
            ImageIO.write(resizedImage, outputFormat, baos);
            imageInBytes = baos.toByteArray();
        } catch (Exception e) {
            throw new Exception("Error on resizing an image: " + e.getMessage());
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(baos);
            if (image != null) {
                image.flush();
            }
            if (resizedImage != null) {
                resizedImage.flush();
            }
        }
        return imageInBytes;
    }
47058
private function _getImageToSize(array $images, int $size)
	{
		$selectedImage = null;
		$selectedSize = 0;

		foreach ($images as $image)
		{
			if (is_array($image))
			{
				$imageWidth = isset($image['width']) && is_numeric($image['width']) ? $image['width'] : 0;
				$imageHeight = isset($image['height']) && is_numeric($image['height']) ? $image['height'] : 0;
				$imageSize = max($imageWidth, $imageHeight);

				if (!$selectedImage ||
					($selectedSize < $size && $imageSize > $selectedSize) ||
					($selectedSize > $imageSize && $imageSize > $size))
				{
					$selectedImage = $image;
					$selectedSize = $imageSize;
				}
			}
		}

		return $selectedImage;
	}
772343
public function forcedImageDownsize($fail, $id, $size) {
        if(empty($size) || empty($id) || is_array($size)) {
            return $fail;
        }

        $meta = wp_get_attachment_metadata($id);

        if(empty($meta)) {
            return $fail;
        }

        if(!isset($meta['sizes'])) {
            return $fail;
        }

        if(!isset($meta['sizes'][$size])) {
            return $fail;
        }

        $isOffloadS3 = (arrayPath($meta, 's3/provider', null) == 'aws');

        $sizeMeta = $meta['sizes'][$size];
        if(!isset($sizeMeta['s3'])) {
            if ($isOffloadS3) {
                if ($this->fixOffloadS3Meta($id, $meta)) {
                    return $this->forcedImageDownsize($fail, $id, $size);
                } else {
                    return $fail;
                }
            } else {
                return $fail;
            }
        }

        $url = $this->getAttachmentURLFromMeta($sizeMeta);// $sizeMeta['s3']['url'];

        $result = [
            $url,
            $sizeMeta['width'],
            $sizeMeta['height'],
            true
        ];

        return $result;
    }
1235599
private function resizeImagick(Imagick $imagick, Picture $picture)
    {
        if(!$this->resizeSmaller && $this->height > $imagick->getImageHeight() && $this->width > $imagick->getImageWidth())
        {
            return;
        }

        if($this->resizeMode === $this::MODE_CROP)
        {
            $imagick->cropThumbnailImage($this->width, $this->height);
        }
        elseif($this->resizeMode === $this::MODE_FILL)
        {
            $ratioH = $this->height / $imagick->getImageHeight();
            $ratioW = $this->width / $imagick->getImageWidth();

            $width  = max($imagick->getImageWidth() * $ratioH, $imagick->getImageWidth() * $ratioW);
            $height = max($imagick->getImageHeight() * $ratioH, $imagick->getImageHeight() * $ratioW);
            $ratio  = max($width / $imagick->getImageWidth(), $height / $imagick->getImageHeight());

            $imagick->scaleImage(round($imagick->getImageWidth() * $ratio), round($imagick->getImageHeight() * $ratio), TRUE);
        }
        elseif($this->resizeMode === $this::MODE_STRETCH)
        {
            $imagick->scaleImage($this->width, $this->height, FALSE);
        }
        elseif($this->resizeMode === $this::MODE_EXACT)
        {
            $imagick->scaleImage($this->width, $this->height, TRUE);

            $rectangle = $picture->createImagick();
            $rectangle->setFormat('png');
            $rectangle->newImage($this->width, $this->height, new \ImagickPixel($this->color ?: 'transparent'));
            $rectangle->compositeImage($imagick, $imagick->getImageCompose(),

                ($rectangle->getImageWidth() - $imagick->getImageWidth()) / 2,
                ($rectangle->getImageHeight() - $imagick->getImageHeight()) / 2
            );

            $picture->setResource($rectangle);
        }
        else
        {
            $imagick->scaleImage($this->width, $this->height, TRUE);
        }
    }
458287
protected function resizeExact(ImageInterface $image, $width, $height)
    {
        return $image->resize(new Box($width, $height));
    }
283717
protected function resizePortrait(ImageInterface $image, $width, $height, $enlarge = true)
    {
        // Don't enlarge a small image
        $box = $image->getSize();
        $ratio = $box->getWidth() / $box->getHeight();

        if ($enlarge === false && $box->getHeight() < $height) {
            $height = $box->getHeight();
        }

        $dimensions = $image->getSize()
            ->heighten($height)
            ->widen($height * $ratio);

        return $image->resize($dimensions);
    }