Create image mosaic in PHP

Question:

What I intend to do is turn an image into a mosaico , where each pixel or group of pixels in the image would be replaced by a photo of a similarly colored flower. That is, transforming any image into a mosaico of flowers. I already have all the logic planned, but the only question I have is how to insert the flower photo in the imagem .

What my código currently does is replace each pixel with another one in a shade of gray. What I want now is to replace that pixel with an imagem .

<?
$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'];
    $nc = round($escala/3); 

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

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

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

Answer:

So far I've managed to allocate each flower photo on the page echoing the img tag , but what I exactly want is to transform it into an image just to save.

<?
$ft = array("imagens/margarida.png","imagens/girassol.png","imagens/rosa.png");

$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'];
    $nc = round((2 * $escala)/765); 

    //echo $nc . ' ';
    echo '<img src="'. $ft[$nc] .'"/>';

    //$cor = imagecolorallocate($gd, $nc, $nc, $nc);

    //imagesetpixel($gd, $i,$j, $cor);
}
echo '<br>';
}

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

For now, it's like this:

normal image

Mosaic

Scroll to Top