PHP code for color correction in photography - ITS UP 2 U - Information


// define image file path
$imagePath = 'path/to/image.jpg';

// create image resource
$image = imagecreatefromjpeg($imagePath);

// get image dimensions
$imageWidth = imagesx($image);
$imageHeight = imagesy($image);

// iterate through each pixel in the image
for ($x = 0; $x < $imageWidth; $x++) {
    for ($y = 0; $y < $imageHeight; $y++) {

        // get the color of the pixel
        $rgb = imagecolorat($image, $x, $y);

        // extract the red, green, and blue components
        $red = ($rgb >> 16) & 0xFF;
        $green = ($rgb >> 8) & 0xFF;
        $blue = $rgb & 0xFF;

        // adjust the color levels as needed
        $red = $red * 1.2;
        $green = $green * 0.9;
        $blue = $blue * 1.1;

        // make sure the color levels are within the 0-255 range
        $red = max(0, min(255, $red));
        $green = max(0, min(255, $green));
        $blue = max(0, min(255, $blue));

        // set the new color of the pixel
        $newRgb = ($red << 16) | ($green << 8) | $blue;
        imagesetpixel($image, $x, $y, $newRgb);

// output the corrected image to the browser or save to a file
header('Content-Type: image/jpeg');

// clean up


This code reads in an image file, creates an image resource using imagecreatefromjpeg(), and then loops through each pixel in the image using nested for loops. For each pixel, the code extracts the red, green, and blue components of the color using bit shifting and masking, and then adjusts the color levels as needed. In this example, the red level is increased by 20%, the green level is decreased by 10%, and the blue level is increased by 10%. The code then sets the new color of the pixel using imagesetpixel(). Finally, the corrected image is output to the browser or saved to a file using imagejpeg(), and the image resource is destroyed using imagedestroy().

Click to listen highlighted text!