Skip to content

Novis\Image\Image::cropped

$image->cropped({…} $box): Image$image->cropped(
    {…} $box,
): Image

Cuts a box out of an image and keeps only that box.

x and y are the top-left corner of the box, in pixels from the top-left corner of the image. width and height are the size of the box. The box must lie completely inside the image and must not be empty. Otherwise encode, encodeVariants or raw throws an error.

cropped returns a new Image and does not change the one you called it on. The work happens when encode, encodeVariants or raw runs.

Good to know: to keep the middle of an image at a fixed shape, resized with both width and height is often easier. It cuts off the edges for you.

Parameters

  • $box{ x: uint, y: uint, width: uint, height: uint }

Return value

Returns Image.

Changelog

VersionChange
0.0.6Each Novis\Image\Image method that returns a new image is named for it, for example resized(), blurred() and withText(). keepingMetadata() replaces metadata({ keep: true }), and encodeVariants() replaces variants(). Image::compare returns a Comparison with the property differenceImage, which was Diff with diff.

Examples

Cut a banner

<?nvs
use Novis\Image\Color;
// Shows how to cut a wide banner out of the middle of a photo.
use Novis\Image\Image;
// A blank 1200 by 800 image replaces a photo that a user uploaded.
Image $photo = Image::create(1200, 800, Color::hex('#336699'));
// The box starts 200 pixels from the top and is 400 pixels high. This prints 1200x400.
var $banner = $photo->cropped({ x: 0, y: 200, width: 1200, height: 400 })->raw();
echo $banner->width, 'x', $banner->height, "\n";
Output
1200x400

Square at the right edge

<?nvs
use Novis\Image\Color;
use Novis\Image\Format;
// Shows how to use the size of an uploaded image to choose the box.
use Novis\Image\Image;
tainted bytes $upload = Image::create(600, 400, Color::hex('#cc6633'))->withFormat(Format::Png)->encode();
// `Image::info` reads the size without decoding the pixels.
// The box is the square at the right edge of the image.
var $info = Image::info($upload);
uint $x = $info->width - $info->height;
// The square starts at x 200 and is 400 pixels wide. This prints 400x400.
var $square = Image::open($upload)->cropped({ x: $x, y: 0, width: $info->height, height: $info->height })->raw();
echo $square->width, 'x', $square->height, "\n";
Output
400x400

Box outside the image

<?nvs
use Novis\Image\Color;
// Shows what happens when the box does not fit inside the image.
use Novis\Image\Image;
Image $photo = Image::create(300, 200, Color::hex('#22aa55'));
// The box ends at x 400, but the image is only 300 pixels wide.
// `cropped` itself does not throw. The error comes from `raw`, which runs the steps.
Image $tooWide = $photo->cropped({ x: 100, y: 0, width: 300, height: 200 });
try {
$tooWide->raw();
echo "cropped\n";
} catch (Throwable $e) {
echo "The box does not fit inside the image.\n";
}
Output
The box does not fit inside the image.