How do I convert RGB values into pixels for an image in PHP?

Asked

Viewed 193 times

4

for ($j = 0; $j < $altura; $j++) {
for ($i = 0; $i < $largura; $i++) {
    $rgb = imagecolorat($img, $i, $j);
    $rgb = imagecolorsforindex($img, $rgb);

    $imagem[$c] = $rgb['red'] + $rgb['green'] + $rgb['blue']; 
    $e = 9;
    $codigo  = round(($e * $imagem[$c])/765);
    echo $codigo;

    $c = $c + 1;
}
echo '<br>';
}

For now, what the code does is convert the RGB values by adding them together to get a number on a scale from 0 to 9. I want you to, instead of printing numbers, print black/gray hued pixels. I mean, I want to convert the image to black and white.

  • Creating Divs and loading the background-color with the colors would not solve?

1 answer

1


<?
$img = imagecreatefrompng('imagens/monalisa.png');
$largura = imagesx($img);
$altura = imagesy($img);

$c = 0;
$imagem = array();

$gd = imagecreatetruecolor($largura, $altura);

for ($j = 0; $j < $altura; $j++) {
   for ($i = 0; $i < $largura; $i++) {
       $rgb = imagecolorat($img, $i, $j);
       $rgb = imagecolorsforindex($img, $rgb);

       $escala = $rgb['red'] + $rgb['green'] + $rgb['blue'];
       $cinza = round($escala/3); 

       $cor = imagecolorallocate($gd, $cinza, $cinza, $cinza);

       imagesetpixel($gd, $i,$j, $cor);
   }
}

header('Content-Type: image/png');
imagepng($gd);
?>

Got it! Someone commented on this link: http://php.net/manual/en/function.imagesetpixel.php, by which I was able to find out what I wanted. Apparently, the comment is gone...

  • I deleted it because I thought it was not what you wanted rs.

  • Worse it was... hahaha thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.