Skip to content

Novis\Image\Image::withGamma

$image->withGamma(float $gamma): Image$image->withGamma(
    float $gamma,
): Image

Makes the middle tones of an image lighter or darker, and keeps black and white.

1.0 changes nothing. A value above 1.0 makes the middle tones lighter, and a value below 1.0 makes them darker. Black stays black and white stays white. This is useful for a photo that is too dark in the shadows but has a correct sky. Transparency does not change.

withGamma 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: withBrightness changes every value by the same factor, so it can turn light parts white. withGamma does not change the lightest and the darkest values.

Parameters

  • $gammafloat

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

Lighter middle tones

<?nvs
use Novis\Image\Color;
// Shows how a gamma above 1.0 makes the middle tones lighter.
use Novis\Image\Image;
Image $shadow = Image::create(10, 10, Color::rgba(64, 64, 64));
// The dark gray 64 becomes the middle gray 128. This prints 128 128 128.
var $raw = $shadow->withGamma(2.0)->raw();
array<mixed> $pixel = Core\Bytes::unpack(Core\Bytes::slice($raw->pixels, 0, 4), 'C4');
echo $pixel[0], ' ', $pixel[1], ' ', $pixel[2], "\n";
Output
128 128 128

Black and white stay

<?nvs
use Novis\Image\Color;
// Shows that `withGamma` does not change black and white.
use Novis\Image\Image;
// This prints 0 and 255, because black and white do not change.
array<Color> $colours = [Color::hex('#000000'), Color::hex('#ffffff')];
foreach ($colours as Color $colour) {
var $raw = Image::create(10, 10, $colour)->withGamma(2.0)->raw();
array<mixed> $pixel = Core\Bytes::unpack(Core\Bytes::slice($raw->pixels, 0, 4), 'C4');
echo $pixel[0], "\n";
}
Output
0
255

Darker middle tones

<?nvs
use Novis\Image\Color;
// Shows how a gamma below 1.0 makes the middle tones darker, for a photo that looks washed out.
use Novis\Image\Image;
Image $pale = Image::create(10, 10, Color::rgba(128, 128, 128));
// The middle gray 128 becomes the dark gray 64. This prints 64 64 64.
var $raw = $pale->withGamma(0.5)->raw();
array<mixed> $pixel = Core\Bytes::unpack(Core\Bytes::slice($raw->pixels, 0, 4), 'C4');
echo $pixel[0], ' ', $pixel[1], ' ', $pixel[2], "\n";
Output
64 64 64