Novis\Image\Image::trimmed
$image->trimmed(?{ threshold?: float } $options = null): Image$image->trimmed( ?{ threshold?: float } $options = null, ): Image
Removes the border around an image.
The border is every row and column at the edge that has the colour of the top-left pixel. trimmed removes these rows and columns and keeps the rest. threshold is how far a colour may differ from the top-left pixel and still count as border. It goes from 0 to 255, and the default is 10. An image that is all border keeps its full size.
trimmed 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: a photo has noise, so its border is rarely one exact colour. A higher threshold removes more of it.
Parameters
$options?{ threshold?: float }default null
Return value
Returns Image.
Changelog
| Version | Change |
|---|---|
0.0.6 | Each 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
Remove empty bands
<?nvsuse Novis\Image\Color;// Shows how to remove the transparent bands above and below a picture.use Novis\Image\Image;
// `Image::Fit::Contain` puts a 400 by 200 picture in a 300 by 300 box.// The box has transparent bands above and below the picture.Image $padded = Image::create(400, 200, Color::hex('#cc3333'))->resized({ width: 300, height: 300, fit: Image::Fit::Contain });
// This prints 300x300 and then 300x150.var $before = $padded->raw();echo $before->width, 'x', $before->height, "\n";var $after = $padded->trimmed()->raw();echo $after->width, 'x', $after->height, "\n";300x300300x150One colour keeps its size
<?nvsuse Novis\Image\Color;// Shows that an image of one colour keeps its full size.use Novis\Image\Image;
// Every pixel has the colour of the top-left pixel. This prints 50x50.var $plain = Image::create(50, 50, Color::hex('#ffffff'))->trimmed()->raw();echo $plain->width, 'x', $plain->height, "\n";50x50Threshold
<?nvsuse Novis\Image\Color;// Shows how `threshold` decides which colours count as border.use Novis\Image\Image;
// A light gray picture sits on a white border. The gray is 15 away from white.Image $scan = Image::create(400, 200, Color::hex('#f0f0f0')) ->resized({ width: 300, height: 300, fit: Image::Fit::Contain }) ->flattened(Color::hex('#ffffff'));
// With the default threshold of 10, the gray is not border. This prints 300x150.var $trimmed = $scan->trimmed()->raw();echo $trimmed->width, 'x', $trimmed->height, "\n";
// With a threshold of 20, the gray counts as border too.// The whole image is border, so it keeps its size. This prints 300x300.var $kept = $scan->trimmed({ threshold: 20.0 })->raw();echo $kept->width, 'x', $kept->height, "\n";300x150300x300