How do you generate a tile map with imagecreate from a php upload?

164 views Asked by At

I have an upload form which accepts multiple file uploads. Each file is 32px x 32px and I am trying to generate an image which contains each image in a grid. every row allows for 30 tiles and the column size is calculated based on the amount of tiles uploaded. For example if there's 120 images there would be 4 columns.

The issue i'm facing is, I cannot seem to calculate the position of each tile in imagecopy. I'm getting the error: "foreach() argument must be of type array|object, string given" for the 2nd foreach loop.

<?php
$num_files = count($_FILES['myFiles']['tmp_name']);

$image = imagecreate(960, ceil(round(30 / $num_files)));

foreach($_FILES['myFiles']['tmp_name'] as $row => $columns) {
    foreach($columns as $col => $filename) {
        $tile = imagecreatefrompng($filename);
        imagecopy($image, $tile, $row * 32, $col * 32, 0, 0, 32, 32);
    }
}

header('Content-Type: image/png');
imagepng($image);
1

There are 1 answers

0
Graigner Jaamesy On

I have figured out a solution that may be helpful to others:

<?php 
$num_files = count($_FILES['myFiles']['tmp_name']);
$tile_size = 32;
$row_size = 20;
$row = 0;
$col = 0;

$image = imagecreate($row_size * $tile_size, round($num_files / 
$row_size) * $tile_size);

foreach($_FILES['myFiles']['tmp_name'] as $files) {

    $tile = imagecreatefrompng($files);
    imagecopy($image, $tile, $row * $tile_size, $col * $tile_size, 0, 0, 
    $tile_size, $tile_size);

    $row++;

    if($row % $row_size == 0) {
        $col++;
        $row = 0;
    }

}

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