Skip to content

Novis\Image\Image::Gravity

A position in an image, written as a direction from the center. Image programs call this position the gravity.

Image::Gravity is declared in the class Novis\Image\Image.

withOverlay and withText use an Image::Gravity as gravity to place the overlay or the text. resized uses it to place the image when fit is Image::Fit::Contain.

When fit is Image::Fit::Cover, the image fills the box and some of it is cut off. The gravity chooses which part resized keeps. Center keeps the middle and is the default. North keeps the top, South the bottom, West the left and East the right. The other four keep a corner. NorthEast keeps the top right and SouthEast the bottom right. SouthWest keeps the bottom left and NorthWest the top left.

For example, a thumbnail of a portrait photo often looks better with North, because the face is usually near the top.

Examples

Keep the left or the right

<?nvs
// Shows how `gravity` chooses which part of an image a square thumbnail keeps.
use Novis\Image\Image;
class FirstPixel
{
public static function of(Image $image): tainted string
{
array<mixed> $p = Core\Bytes::unpack(Core\Bytes::slice($image->raw()->pixels, 0, 4), 'C4');
return "{$p[0]} {$p[1]} {$p[2]}";
}
}
// An image of 2 by 1 pixels: red on the left and blue on the right.
Image $banner = Image::fromRaw({
width: 2,
height: 1,
pixels: Core\Encoding::fromHex('ff0000ff0000ffff'),
});
// A thumbnail of 1 by 1 pixel can keep only one of them.
// `West` keeps the red pixel and prints 255 0 0. `East` keeps the blue one and prints 0 0 255.
echo FirstPixel::of($banner->resized({ width: 1, height: 1, fit: Image::Fit::Cover, gravity: Image::Gravity::West })), "\n";
echo FirstPixel::of($banner->resized({ width: 1, height: 1, fit: Image::Fit::Cover, gravity: Image::Gravity::East })), "\n";
Output
255 0 0
0 0 255