0

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);
  • Can you `print_r( $_FILES );` so we might be able to see what your array looks like to start with? -- Obviously `foreach($_FILES['myFiles']['tmp_name'] as $row => $columns) {` is setting `$columns` as a string and not an array. – Zak Jun 14 '22 at 21:08
  • When dealing with multiple file uploads ( as appears to be the case here ) you use syntax like `foreach( $_FILES['myFiles']['name'] as $i => $void )` and then, within the loop, use `$name = $_FILES['myFiles']['name'][$i];` - the `$void` variable is unused thereafter – Professor Abronsius Jun 14 '22 at 21:16

1 Answers1

0

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