Search code examples
phpimagegenerate

Generate pixels from image template in php not working :(


I tried this code to generate pixels around a black and white template, but it only gives me scrambled machine code.

Can anyone tell my how to fix it, or why exactly this happens?

https://nowat.org/test44.php

<?php
// Load the image of Nelson Mandela
$original = imagecreatefromjpeg('https://www.bigissue.org.za/wp-content/uploads/2016/07/Nelson-Mandela_AFP-Photo-2.jpg');

// Get the dimensions of the original image
$width = imagesx($original);
$height = imagesy($original);

// Create a blank image with the same dimensions
$image = imagecreatetruecolor($width, $height);

// Generate random pixels
for ($x = 0; $x < $width; $x++) {
    for ($y = 0; $y < $height; $y++) {
        // Get the color of the current pixel from the original image
        $rgb = imagecolorat($original, $x, $y);
        $colors = imagecolorsforindex($original, $rgb);
        
        // Generate a random color variation
        $red = rand($colors['red'] - 50, $colors['red'] + 50);
        $green = rand($colors['green'] - 50, $colors['green'] + 50);
        $blue = rand($colors['blue'] - 50, $colors['blue'] + 50);
        $color = imagecolorallocate($image, $red, $green, $blue);
        
        // Set the pixel color
        imagesetpixel($image, $x, $y, $color);
    }
}

// Output the image as a PNG
header('Content-Type: image/png');
imagepng($image);

// Clean up
imagedestroy($image);

?>

Any Help appreciated!


Solution

  • Your random color are not correct. Color must be between 0 and 255.

    ...
    var_dump($red, $blue, $green);
    ...
    
    int(261) <--- HERE
    PHP Fatal error:  Uncaught ValueError: imagecolorallocate(): Argument #2 ($red) must be between 0 and 255 (inclusive) in test.php:24
    Stack trace:
    #0 test.php(24): imagecolorallocate()
    #1 {main}
      thrown in test.php on line 24
    
    

    Try this:

    $red = abs(rand($colors['red'] - 50, $colors['red'] + 50) % 255);
    $green = abs(rand($colors['green'] - 50, $colors['green'] + 50) % 255);
    $blue = abs(rand($colors['blue'] - 50, $colors['blue'] + 50) % 255);
    

    Result here