Skip to content

Novis\Image\Image::grayscaled

$image->grayscaled(): Image

Removes the colours of an image and keeps how light or dark each pixel is.

Every pixel gets the same red, green and blue value. The value is how light the pixel looks to a person. Green counts more than red, and red counts more than blue. Transparency does not change.

grayscaled 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 give a gray image one colour, for example an old brown photo, call tinted after grayscaled.

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

One pixel

<?nvs
use Novis\Image\Color;
// Shows the gray value that `grayscaled` gives a red, a green and a blue pixel.
use Novis\Image\Image;
// Green looks lightest to a person, and blue looks darkest.
// This prints 54 54 54, then 182 182 182, then 18 18 18.
array<Color> $colours = [Color::hex('#ff0000'), Color::hex('#00ff00'), Color::hex('#0000ff')];
foreach ($colours as Color $colour) {
var $raw = Image::create(4, 4, $colour)->grayscaled()->raw();
array<mixed> $pixel = Core\Bytes::unpack(Core\Bytes::slice($raw->pixels, 0, 4), 'C4');
echo $pixel[0], ' ', $pixel[1], ' ', $pixel[2], "\n";
}
Output
54 54 54
182 182 182
18 18 18

Gray thumbnail

<?nvs
use Novis\Image\Color;
use Novis\Image\Format;
// Shows how to make a small gray JPEG for a list of archived items.
use Novis\Image\Image;
Image $photo = Image::create(800, 600, Color::hex('#cc6633'));
// This prints image/jpeg 160x120.
tainted bytes $jpeg = $photo->resized({ width: 160 })->grayscaled()->withFormat(Format::Jpeg, { quality: 70 })->encode();
var $info = Image::info($jpeg);
echo Image::mime($info->format), ' ', $info->width, 'x', $info->height, "\n";
Output
image/jpeg 160x120

Transparency stays

<?nvs
use Novis\Image\Color;
// Shows that `grayscaled` keeps the transparency of each pixel.
use Novis\Image\Image;
Image $icon = Image::create(4, 4, Color::rgba(255, 255, 255, 0.5));
// White stays white, and the alpha stays half. This prints 255 255 255 128.
var $raw = $icon->grayscaled()->raw();
array<mixed> $pixel = Core\Bytes::unpack(Core\Bytes::slice($raw->pixels, 0, 4), 'C4');
echo $pixel[0], ' ', $pixel[1], ' ', $pixel[2], ' ', $pixel[3], "\n";
Output
255 255 255 128