Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to apply a gamma correction to a Graphics Draw (GD) image in PHP?
The imagegammacorrect() function is an inbuilt PHP function that applies gamma correction to a Graphics Draw (GD) image. Gamma correction adjusts the brightness and contrast of an image by modifying the relationship between input and output pixel values.
Syntax
bool imagegammacorrect(resource $image, float $inputgamma, float $outputgamma)
Parameters
The imagegammacorrect() function takes three parameters ?
$image − The image resource to apply gamma correction to
$inputgamma − The input gamma value (typically between 0.1 and 10.0)
$outputgamma − The output gamma value (typically between 0.1 and 10.0)
Return Values
Returns TRUE on success or FALSE on failure.
Example
Here's how to apply gamma correction to brighten an image ?
<?php
// Create a sample image
$img = imagecreate(200, 200);
// Allocate colors
$white = imagecolorallocate($img, 255, 255, 255);
$gray = imagecolorallocate($img, 128, 128, 128);
$dark = imagecolorallocate($img, 64, 64, 64);
// Fill background
imagefill($img, 0, 0, $white);
// Draw some shapes with different shades
imagefilledellipse($img, 50, 50, 80, 80, $gray);
imagefilledellipse($img, 150, 150, 80, 80, $dark);
// Apply gamma correction to brighten the image
// Input gamma: 1.0 (no input correction)
// Output gamma: 0.5 (brightens the image)
$result = imagegammacorrect($img, 1.0, 0.5);
if ($result) {
echo "Gamma correction applied successfully!";
// Output image to browser
header('Content-Type: image/png');
imagepng($img);
} else {
echo "Gamma correction failed!";
}
// Clean up memory
imagedestroy($img);
?>
How Gamma Correction Works
Gamma correction uses the formula: output = input^(inputgamma/outputgamma). Values less than 1.0 brighten the image, while values greater than 1.0 darken it ?
Output gamma < 1.0 − Brightens the image
Output gamma > 1.0 − Darkens the image
Output gamma = 1.0 − No change in brightness
Conclusion
The imagegammacorrect() function provides an effective way to adjust image brightness and contrast in PHP. Use values below 1.0 for the output gamma to brighten images, or above 1.0 to darken them.
