Crops image via rectangle

@param array $rectangle
@throws ImageException If couldn't crop image.
512077
public function crop(array $rectangle) {
        $croppedImage = @imagecrop($this->resource, $rectangle);
        if($croppedImage === false) {
            $rectangleAsString = "{";
            foreach($rectangle as $key => $value) {
                $rectangleAsString .= "\"{$key}\" => {$value}, ";
            }
            $rectangleAsString = preg_replace("/, $/", "}", $rectangleAsString);
            throw new ImageException(
                "Can not crop image {$this} via rectangle {$rectangleAsString}.",
                ImageException::GenericException
            );
        }
        $this->resource = $croppedImage;
        $this->width = $rectangle["width"];
        $this->height = $rectangle["height"];
    }
264693
public function crop($x, $y, $x2, $y2) {
		$width = $x2 - $x;
		$height = $y2 - $y;
		$image = imagecreatetruecolor($width, $height);
		imagecopy($image, $this->_image, 0, 0, $x, $y, $width, $height);
		imagedestroy($this->_image);
		$this->_image = $image;
		return $this;
	}
1118574
public function crop( $x, $y, $width, $height )
	{
		// check for auto
		if ( $x == 'center' || $x == 'auto' )
		{
			$x = ( $this->width / 2 ) - ( $width / 2 );
		}

		if ( $y == 'middle' || $y == 'auto' )
		{
			$y = ( $this->height / 2 ) - ( $height / 2 );
		}

		$result = imagecreatetruecolor( $width, $height );  
		ImageCopyResampled( $result, $this->image_context, 0, 0, $x, $y, $width, $height, $width, $height );

		$this->image_context = $result;

		// update properties
		$this->reload_context_info();

		// return self
		return $this;
	}
1209694
public function crop(Dimension $dimension)
    {
        $resampleImageResource =& $this->getResampleImageResource();

        if (false !== ($resampleCropImage = imagecrop($resampleImageResource, [
                'x'      => $dimension->getAxis()->getX(),
                'y'      => $dimension->getAxis()->getY(),
                'width'  => $dimension->getWidth(),
                'height' => $dimension->getHeight(),
            ]))
        ) {
            $resampleImageResource = $resampleCropImage;

            return true;
        }

        return false;
    }
870696
def handle_sub_rectangles(self, images, sub_rectangles):
        
        image_info = [im.info for im in images]
        if isinstance(sub_rectangles, (tuple, list)):
            # xy given directly

            # Check xy
            xy = sub_rectangles
            if xy is None:
                xy = (0, 0)
            if hasattr(xy, '__len__'):
                if len(xy) == len(images):
                    xy = [xxyy for xxyy in xy]
                else:
                    raise ValueError("len(xy) doesn't match amount of images.")
            else:
                xy = [xy for im in images]
            xy[0] = (0, 0)

        else:
            # Calculate xy using some basic image processing

            # Check Numpy
            if np is None:
                raise RuntimeError("Need Numpy to use auto-sub_rectangles.")

            # First make numpy arrays if required
            for i in range(len(images)):
                im = images[i]
                if isinstance(im, Image.Image):
                    tmp = im.convert()  # Make without palette
                    a = np.asarray(tmp)
                    if len(a.shape) == 0:
                        raise MemoryError("Too little memory to convert PIL image to array")
                    images[i] = a

            # Determine the sub rectangles
            images, xy = self.get_sub_rectangles(images)

        # Done
        return images, xy, image_info
493877
protected function createCrop($crop, $image)
	{
		if (!empty($crop['cropped_field'])) {
			$save_path = $this->getUploadPath($crop['cropped_field']);
		} else {
			$save_path = $this->getUploadPath($this->attribute);
		}

		$sizes = explode('-', $crop['value']);

		$real_size = $image->getSize();

		foreach ($sizes as $ind => $cr) {
			$sizes[$ind] = round($sizes[$ind]*($ind%2 == 0 ? $real_size->getWidth() : $real_size->getHeight())/100);
		}

		$crop_image = $image->crop(new Point($sizes[0], $sizes[1]), new Box($sizes[2]-$sizes[0], $sizes[3]-$sizes[1]));

		if (!empty($crop['crop_width']))
			$crop_image = $crop_image->resize(new Box($crop['crop_width'], $crop['crop_width'] / $crop['ratio']));

		$crop_image->save($save_path, isset($crop['save_options']) ? $crop['save_options'] : $this->save_options);
	}
1225439
private function applyFormatCrop(ImageInterface $image, array $cropParameters)
    {
        return $this->modifyAllLayers(
            $image,
            function(ImageInterface $layer) use ($cropParameters) {
                return $this->cropper->crop(
                    $layer,
                    $cropParameters['x'],
                    $cropParameters['y'],
                    $cropParameters['width'],
                    $cropParameters['height']
                );
            }
        );
    }
1028803
public function setFormat($format)
    {
        if (!in_array($format, self::$formats)) {
            throw new ImageException('Invalid image format provided. Supported formats are [jpg, jpeg, png, gif].');
        }

        $this->format = $format;
    }
759448
public function crop($x, $y, $width, $height)
    {
        $oCanvas = imagecreatetruecolor($width, $height);
        imagecopyresampled($oCanvas, $this->oImg, 0, 0, $x, $y, $width, $height, $width, $height);
        $this->oImg = $oCanvas;
        return $this;
    }
808327
public function crop($x, $y, $width, $height, $interlace = false) {
		return $this -> createImage($x, $y, $width, $height, $width, $height, $interlace);
	}
21201
public void setCropArea(int x, int y, int width, int height) {

        m_cropX = x;
        m_cropY = y;
        m_cropWidth = width;
        m_cropHeight = height;
    }
1073840
private function calculateCrop(array $parameters, array $imageSize) {
        $focalX = $parameters['poi'][0];
        $focalY  = $parameters['poi'][1];

        $sourceWidth = $imageSize['width'];
        $sourceHeight = $imageSize['height'];
        $sourceRatio  = $sourceWidth / $sourceHeight;

        $targetWidth = $parameters['width'];
        $targetHeight = $parameters['height'];
        $targetRatio  = $targetWidth / $targetHeight;

        $growFactor = $this->getGrowFactor($parameters['closeness']);
        $sourcePortionThreshold = $this->getSourcePercentageThreshold($parameters['closeness']);

        if ($sourceRatio >= $targetRatio) {
            // Image is wider than needed, crop from the sides
            $cropWidth = (int) ceil(
                $targetRatio * max(
                    min($sourceHeight, $targetHeight * $growFactor),
                    $sourceHeight * $sourcePortionThreshold
                )
            );
            $cropHeight = (int) floor($cropWidth / $targetRatio);
        } else {
            // Image is taller than needed, crop from the top/bottom
            $cropHeight = (int) ceil(
                max(
                    min($sourceWidth, $targetWidth * $growFactor),
                    $sourceWidth * $sourcePortionThreshold
                ) / $targetRatio
            );
            $cropWidth = (int) floor($cropHeight * $targetRatio);
        }

        $cropTop = (int) ($focalY - floor($cropHeight / 2));
        $cropLeft = (int) ($focalX - floor($cropWidth / 2));

        // Make sure that we're not cropping outside the image on the x axis
        if ($cropLeft < 0) {
            $cropLeft = 0;
        } else if ($cropLeft + $cropWidth > $sourceWidth) {
            $cropLeft = $sourceWidth - $cropWidth;
        }

        // Make sure that we're not cropping outside the image on the y axis
        if ($cropTop < 0) {
            $cropTop = 0;
        } else if ($cropTop + $cropHeight > $sourceHeight) {
            $cropTop = $sourceHeight - $cropHeight;
        }

        return [
            'width' => $cropWidth,
            'height' => $cropHeight,
            'x' => $cropLeft,
            'y' => $cropTop,
        ];
    }
1109089
public function cropToFit($width, $height, $focusPointX = 0, $focusPointY = 0)
    {

        $debug = $width == 100 && $height == 100;

        // Check if the image is a valid resource
        if (!is_resource($this->image)) {
            throw new RuntimeException('No image set');
        }

        // Get the width and height of element
        $originalWidth = imagesx( $this->image );
        $originalHeight = imagesy( $this->image );

        // Check if any of the width and height is null, and set it to the $source size
        $width = $width ?: $originalWidth;
        $height = $height ?: $originalHeight;

        // Calculate the aspect ratio of the existing image
        $originalAspectRatio = $originalWidth / $originalHeight;

        // Calculate the aspect ratio of the desired image
        $desiredAspectRatio = $width / $height;

        // Check what value we should use with the aspect ratio
        if ( $originalAspectRatio > $desiredAspectRatio ) {
            $temp_height = $height;
            $temp_width = ( int ) ($height * $originalAspectRatio);
        }
        else {
            $temp_width = $width;
            $temp_height = ( int ) ($width / $originalAspectRatio);
        }

        // Get the center of image based on the focusPoint
        $x0 = ( $temp_width - $width ) * ( ( $focusPointX + 1 ) * .5 );
        $y0 = ( $temp_height - $height ) * ( ( $focusPointY + 1 ) * .5 );

        // If $x0 or $y0 is not a full number increase with one pixel
        // to fill black line and fill canvas
        if ( ! ctype_digit( $x0 ) || ! ctype_digit( $y0 ) ) {
            $temp_width++;
            $temp_height++;
        }

        // Resize the image into the desired image
        $this->resize( $temp_width, $temp_height );

        // Create canvas for the new image
        $canvas = $this->createCanvas( $width, $height );
        // Do the cropping of image
        imagecopy( $canvas, $this->image, 0, 0, $x0, $y0, $width, $height );

        // Replace the image
        $this->replace( $canvas );

        // Return $this for chaining
        return $this;
    }
515354
public function crop($x1, $y1, $x2, $y2)
    {
        if ($x2 < $x1) {
            list($x1, $x2) = array($x2, $x1);
        }
        if ($y2 < $y1) {
            list($y1, $y2) = array($y2, $y1);
        }

        $crop_width = $x2 - $x1;
        $crop_height = $y2 - $y1;

        $new = imagecreatetruecolor($crop_width, $crop_height);

        if (empty($new)) {
            throw new UnexpectedValueException('Failed to create an image identifier');
        }

        imagealphablending($new, false);
        imagesavealpha($new, true);

        if (!imagecopyresampled($new, $this->image, 0, 0, $x1, $y1, $crop_width, $crop_height, $crop_width, $crop_height)) {
            throw new UnexpectedValueException('Failed to copy and resize part of an image with resampling');
        }

        $this->image = $new;
        $this->width = $crop_width;
        $this->height = $crop_height;

        return $this;
    }
1155174
public function crop($x, $y, $w, $h) {

        $new = @imagecreatetruecolor($w, $h);

        // This needed to deal with .png transparency
        imagealphablending($new, false);
        imagesavealpha($new, true);
        $transparent = imagecolorallocatealpha($new, 255, 255, 255, 127);
        imagefilledrectangle($new, 0, 0, $w, $h, $transparent);

        if($new === FALSE) {
            throw new Exception('Cannot Initialize new GD image stream');
            return;
        }
        imagecopyresampled($new, $this->resource, 0, 0, $x, $y, $w, $h, $w, $h);
        $this->resource = $new;

        // for method chaining
        return $this;
    }
999838
public function collect(Map $map, array $rectangles = [])
    {
        return $this->collectValues($map->getOverlayManager()->getRectangles(), $rectangles);
    }
723659
public function crop($w, $h, $x = 0, $y = 0, $width = null, $height = null){
        $this->img->crop($w, $h, $x, $y, $width, $height);
        return $this;
    }