Get the topleftX and topleftY that will can be passed to a cropping method.

@param  \Imagick $original
@param  int      $targetWidth
@param  int      $targetHeight
@return array
185024
protected function getEntropyOffsets(\Imagick $original, $targetWidth, $targetHeight)
    {
        $measureImage = clone($original);
        // Enhance edges
        $measureImage->edgeimage(1);
        // Turn image into a grayscale
        $measureImage->modulateImage(100, 0, 100);
        // Turn everything darker than this to pitch black
        $measureImage->blackThresholdImage("#070707");
        // Get the calculated offset for cropping
        return $this->getOffsetFromEntropy($measureImage, $targetWidth, $targetHeight);
    }
358304
def fitToSize(rect, targetWidth, targetHeight, bounds):
	
	
	# Determine the difference between the current size and target size
	x,y,w,h = rect
	diffX = w - targetWidth
	diffY = h - targetHeight
	
	# Determine if we are cropping or padding the width
	if diffX > 0:
		cropLeft  = math.floor(diffX / 2)
		cropRight = diffX - cropLeft
		x,y,w,h   = cropRect((x,y,w,h), 0, 0, cropLeft, cropRight)
	elif diffX < 0:
		padLeft  = math.floor(abs(diffX) / 2)
		padRight = abs(diffX) - padLeft
		x,y,w,h  = padRect((x,y,w,h), 0, 0, padLeft, padRight, bounds, False)
	
	# Determine if we are cropping or padding the height
	if diffY > 0:
		cropTop    = math.floor(diffY / 2)
		cropBottom = diffY - cropTop
		x,y,w,h    = cropRect((x,y,w,h), cropTop, cropBottom, 0, 0)
	elif diffY < 0:
		padTop    = math.floor(abs(diffY) / 2)
		padBottom = abs(diffY) - padTop
		x,y,w,h   = padRect((x,y,w,h), padTop, padBottom, 0, 0, bounds, False)
	
	return (x,y,w,h)
953768
function getSVGContentRect(target) {
    const bbox = target.getBBox();

    return createRectInit(0, 0, bbox.width, bbox.height);
}
1122532
public function resizeImage($newWidth, $newHeight, $crop = false)
    {
        $newWidth = intval($newWidth);
        $newHeight = intval($newHeight);
        $resampleImageFile = $this->driver->getSourceImageFile();
        $resampleDimension = $resampleImageFile->getDimension();
        $resampleDimension->maintainAspectRatio = $this->config->offsetGet('maintainAspectRatio');

        if ($newWidth == $newHeight) {
            $this->driver->setResampleImage($resampleImageFile->withDimension(
                $resampleDimension
                    ->withOrientation('SQUARE')
                    ->withFocus('CENTER')
                    ->withSize($newWidth, $newHeight)
            ));

            return $this->driver->resize(true);
        } else {
            $this->driver->setResampleImage($resampleImageFile->withDimension(
                $resampleDimension
                    ->withDirective($this->config->offsetGet('scaleDirective'))
                    ->withOrientation($this->config->offsetGet('orientation'))
                    ->withFocus($this->config->offsetGet('focus'))
                    ->withSize($newWidth, $newHeight)
            ));

            return $this->driver->resize($crop);
        }
    }
591621
public static Sprite flipV(Sprite original) {
		int[] newPix = new int[original.getPixels().length];

		for (int x = 0; x < original.getWidth(); x++) {
			int newX = original.getWidth() - x - 1;
			for (int y = 0; y < original.getHeight(); y++) {
				newPix[newX + y * original.getWidth()] = original.getPixels()[x + y * original.getWidth()];
			}
		}
		return new Sprite(original.getWidth(), original.getHeight(), newPix);
	}
769513
public function createCroppedImageVariant(ImageSize $sourceImageSize, $targetWidth, $targetHeight, $cropped = false, $quality = 95, $force = false)
	{
		// validate params
		if ( ! $sourceImageSize instanceof ImageSize) {
			throw new Exception\RuntimeException('ImageSize entity expected');
		}
		if (($targetWidth <= 0) || ($targetHeight <= 0)) {
			throw new Exception\RuntimeException('Dimensions are invalid');
		}
		
		if ( ! $sourceImageSize->isCropped()) {
			//throw new Exception\RuntimeException('Cannot resize non-cropped images with this metod');
		}
		
		$image = $sourceImageSize->getMaster();

		$sizeName = $this->getImageSizeNameForResizedCrop($targetWidth, $targetHeight, $sourceImageSize->getTargetWidth(), $sourceImageSize->getTargetHeight(), $sourceImageSize->getCropLeft(), $sourceImageSize->getCropTop(), $sourceImageSize->getCropWidth(), $sourceImageSize->getCropHeight(), $cropped);
			
		if ( ! $this->fileExists($image)) {
			$this->log()->warn("Image '{$image->getFileName()}' is missing in the filesystem, tried to resize cropped variant to {$sizeName}");

			return $sizeName;
		}
		
		$size = $image->getImageSize($sizeName);

		if (($size->getTargetHeight() == $targetHeight)
				&& ($size->getTargetWidth() == $targetWidth)
				&& ($size->getQuality() == $quality)
				&& ($size->getCropMode() == $cropped)
				&& empty($force)
		) {
			// nothing to update
			return $sizeName;
		}
		
		$size->setCropTop($sourceImageSize->getCropTop());
		$size->setCropLeft($sourceImageSize->getCropLeft());
		$size->setCropWidth($sourceImageSize->getCropWidth());
		$size->setCropHeight($sourceImageSize->getCropHeight());
		
		$size->setCropSourceWidth($sourceImageSize->getWidth());
		$size->setCropSourceHeight($sourceImageSize->getHeight());
	
		$size->setQuality($quality);
		$size->setCropMode($cropped);
		$size->setTargetWidth($targetWidth);
		$size->setTargetHeight($targetHeight);

		$variantFileName = $this->getImagePath($image, $sourceImageSize->getName());

		if ( ! file_exists($variantFileName)) {
			$this->log()->warn("Image cropped variant file {$variantFileName} is missing in the filesystem");

			return $sizeName;
		}
		
		$resizer = $this->getImageResizer();
		
		$resizer->setSourceFile($variantFileName)
				->setOutputQuality($quality)
				->setTargetWidth($targetWidth)
				->setTargetHeight($targetHeight)
				->setCropMode($cropped);

		$expectedSize = $resizer->getExpectedSize();
		$size->setWidth($expectedSize['width']);
		$size->setHeight($expectedSize['height']);

		$resizedFileDir = $this->getFilesystemDir($image)
				. self::RESERVED_DIR_SIZE . DIRECTORY_SEPARATOR
				. $size->getFolderName();

		if ( ! file_exists($resizedFileDir)) {
			$mkdirResult = mkdir($resizedFileDir, $this->folderAccessMode, true);
			if (empty($mkdirResult)) {
				throw new Exception\RuntimeException(
						'Could not create directory for resized image');
			}
		}

		$resizedFilePath = $resizedFileDir . DIRECTORY_SEPARATOR . $image->getFileName();
		$resizer->setOutputFile($resizedFilePath);
		$resizer->process();

		$entityManager = $this->getDoctrineEntityManager();

		$entityManager->persist($size);
		
		$size->setCropSourceWidth($sourceImageSize->getWidth());
		$size->setCropSourceHeight($sourceImageSize->getHeight());
		
		$entityManager->flush();

		return $sizeName;
	}
308340
public function crop($width, $height, $startX = null, $startY = null)
    {
        if ($width === null) {
            $width = $this->width;
        }

        if ($height === null) {
            $height = $this->height;
        }

        if ($startX === null) {
            $startX = floor(($this->width - $width) / 2);
        }

        if ($startY === null) {
            $startY = floor(($this->height - $height) / 2);
        }

        // Calculate dimensions
        $startX = max(0, min($this->width, $startX));
        $startY = max(0, min($this->height, $startY));
        $width = min($width, $this->width - $startX);
        $height = min($height, $this->height - $startY);

        $image = imagecreatetruecolor($width, $height);
        $this->preserveTransparency($image);

        imagecopyresampled($image, $this->image, 0, 0, $startX, $startY, $width, $height, $width, $height);
        $this->setImage($image);
        $this->width = $width;
        $this->height = $height;

        return $this;
    }
791220
private function crop($optimal_width, $optimal_height, $new_width, $new_height)
    {
        // Find center - this will be used for the crop
        $crop_start_x = ($optimal_width  / 2) - ($new_width  / 2);
        $crop_start_y = ($optimal_height / 2) - ($new_height / 2);

        $crop = $this->image_resized;

        $dest_offset_x = max(0, -$crop_start_x);
        $dest_offset_y = max(0, -$crop_start_y);
        $crop_start_x  = max(0, $crop_start_x);
        $crop_start_y  = max(0, $crop_start_y);
        $dest_width    = min($optimal_width, $new_width);
        $dest_height   = min($optimal_height, $new_height);

        // Now crop from center to exact requested size
        $this->image_resized = imagecreatetruecolor($new_width, $new_height);

        imagealphablending($crop, true);
        imagealphablending($this->image_resized, false);
        imagesavealpha($this->image_resized, true);

        imagefilledrectangle($this->image_resized, 0, 0, $new_width, $new_height,
            imagecolorallocatealpha($this->image_resized, 255, 255, 255, 127)
        );

        imagecopyresampled($this->image_resized, $crop, $dest_offset_x, $dest_offset_y, $crop_start_x, $crop_start_y, $dest_width, $dest_height, $dest_width, $dest_height);

        return true;
    }
826110
private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
    {
        // *** Find center - this will be used for the crop
        $cropStartX = ($optimalWidth / 2) - ($newWidth / 2);
        $cropStartY = ($optimalHeight / 2) - ($newHeight / 2);

        $crop = $this->imageResized;
        //imagedestroy($this->imageResized);
        // *** Now crop from center to exact requested size
        $this->imageResized = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($this->imageResized, $crop, 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight, $newWidth, $newHeight);
    }
1347833
public static function resize(\Imagick $source, int $boxWidth, int $boxHeight, array $options = []) : \Imagick
    {
        $results = self::resizeMulti($source, [['width' => $boxWidth, 'height' => $boxHeight]], $options);
        return $results[0];
    }
1288606
def outbound_sizes(cls, original_width, original_height, target_width, target_height):
        
        if target_width <= original_width and target_height <= original_height:
            k = original_width / float(original_height)
            k_w = original_width / float(target_width)
            k_h = original_height / float(target_height)

            if k_w > k_h:
                target_width = int(target_height * k)
            else:
                target_height = int(target_width / k)
        else:
            target_width = original_width
            target_height = original_height

        return target_width, target_height
373118
protected function getOffsetFromEntropy(\Imagick $originalImage, $targetWidth, $targetHeight)
    {
        // The entropy works better on a blured image
        $image = clone $originalImage;
        $image->blurImage(3, 2);

        $size = $image->getImageGeometry();

        $originalWidth = $size['width'];
        $originalHeight = $size['height'];

        $leftX = $this->slice($image, $originalWidth, $targetWidth, 'h');
        $topY = $this->slice($image, $originalHeight, $targetHeight, 'v');

        return array('x' => $leftX, 'y' => $topY);
    }
97389
private function verifySize($originalWidth, $originalHeight, $targetWidth, $targetHeight)
    {
        if ($originalWidth < $targetWidth && $originalHeight < $targetHeight) {
            return array(
                'width' => $originalWidth,
                'height' => $originalHeight,
            );
        }

        return array(
            'width' => $targetWidth,
            'height' => $targetHeight,
        );
    }
82667
private function resizeByHeight($originalWidth, $originalHeight, $targetHeight)
    {
        $targetWidth = ($targetHeight * $originalWidth) / $originalHeight;

        return $this->verifySize($originalWidth, $originalHeight, $targetWidth, $targetHeight);
    }
599266
public function doFilter($originalImage, $arguments, $imageOptions)
    {
        // Need at least a height or a width
        if (empty($arguments['height']) && empty($arguments['width'])) {
            throw new ErrorException('You must set at least the height (h) or the width (w)');
        }
        switch (strtolower($imageOptions['imageProcessor'])) {
            case 'gd':
                $Imagine = new \Imagine\Gd\Imagine();
                break;
            case 'imagick':
                $Imagine = new \Imagine\Imagick\Imagine();
                break;
            case 'gmagick':
                $Imagine = new \Imagine\Gmagick\Imagine();
                break;
            default:
                throw new ErrorException('Unsupported imageProcessor config value: ' . $imageOptions['imageProcessor']);
        }
        $image = $Imagine->open($originalImage);

        $size = $image->getSize();
        $originalWidth = $size->getWidth();
        $originalHeight = $size->getHeight();
        $width = $originalWidth;
        $height = $originalHeight;

        if (! empty($arguments['height'])) {
            if ($originalHeight > $arguments['height'] || $arguments['stretch']) {
                $height = $arguments['height'];
            }
        }
        if (! empty($arguments['width'])) {
            if ($originalWidth > $arguments['width'] || $arguments['stretch']) {
                $width = $arguments['width'];
            }
        }

        /**
         * Prevent from someone from creating huge images
         */
        if ($width > $imageOptions['maxAllowedResizeWidth']) {
            $width = $imageOptions['maxAllowedResizeWidth'];
        }

        if ($height > $imageOptions['maxAllowedResizeHeight']) {
            $height = $imageOptions['maxAllowedResizeHeight'];
        }

        $mode = $arguments['exact'] ?
            ImageInterface::THUMBNAIL_OUTBOUND :
            ImageInterface::THUMBNAIL_INSET;

        $newSize = new Box($width, $height);

        $newImage = $image->thumbnail($newSize, $mode);
        if ($arguments['fill']) {
            $adjustedSize = $newImage->getSize();
            $canvasWidth = isset($arguments['width']) ? $arguments['width'] : $adjustedSize->getWidth();
            $canvasHeight = isset($arguments['height']) ? $arguments['height'] : $adjustedSize->getHeight();
            /**
             * Prevent from someone from creating huge images
             */
            if ($canvasWidth > $imageOptions['maxAllowedResizeWidth']) {
                $canvasWidth = $imageOptions['maxAllowedResizeWidth'];
            }

            if ($canvasHeight > $imageOptions['maxAllowedResizeHeight']) {
                $canvasHeight = $imageOptions['maxAllowedResizeHeight'];
            }

            $palette = new RGB();
            $canvas = $Imagine->create(
                new Box($canvasWidth, $canvasHeight),
                $palette->color($arguments['fillColour'])
            );

            // Put image in the middle of the canvas
            $newImage = $canvas->paste($newImage, new Point(
                (int) (($canvasWidth - $adjustedSize->getWidth()) / 2),
                (int) (($canvasHeight - $adjustedSize->getHeight()) / 2)
            ));
        }

        $newImage->save($originalImage, array('jpeg_quality' => $arguments['quality']));
    }
1059363
public function thumbnail($image, $targetWidth = 100, $targetHeight = 100)
    {
        $imagePath = $this->container->getParameter('red_kite_cms.web_folder_full_path') . $image;
        if (!is_file($imagePath)) {
            return null;
        }
        $thumbnailer = $this->container->get('red_kite_cms.images_thumbnailer');
        $thumbnailer->create($imagePath, $targetWidth, $targetHeight);

        return sprintf('<img src="%s" width="%s" height="%s" rel="%s" />', dirname($image) .  '/' . $thumbnailer->getThumbnailFolder() . '/' . $thumbnailer->getThumbnailImageName(), $thumbnailer->getThumbnailWidth(), $thumbnailer->getThumbnailHeight(), $image);
    }
593271
public static <T extends ImageGray<T>> T checkReshape(T target , ImageGray testImage , Class<T> targetType )
	{
		if( target == null ) {
			return GeneralizedImageOps.createSingleBand(targetType, testImage.width, testImage.height);
		} else if( target.width != testImage.width || target.height != testImage.height ) {
			target.reshape(testImage.width,testImage.height);
		}
		return  target;
	}