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

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 the time being, what the code does is convert the RGB values by adding them to get a number on a scale of 0 to 9. I want instead of printable numbers, printe pixels of black / gray tones. That is, I want to convert the image to black and white.

    
asked by anonymous 11.09.2017 / 22:08

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);
?>

I did it! Someone commented on this link: link , by which I was able to find out what I wanted. Apparently, the comment disappeared ...

    
11.09.2017 / 22:47