1

I have 4 small JPEG images (40px x 30px) and I want create an image of tiles using GD.

Two at the top and two at the bottom row.

Like this:

[][]
[][]

How can that be done?

hakre
  • 193,403
  • 52
  • 435
  • 836
user622378
  • 2,318
  • 6
  • 42
  • 63

1 Answers1

5

The functions you'll need to use are

  • getimagesize - Get the width and height so you know what size to make the final image, unless you want to hardcode it.
  • imagecreate - Create resource for the merged image.
  • imagecreatefromjpeg - Load the existing tiles as resources.
  • imagecopy - Copy the existing tiles into the new image resource, you shouldn't need the resampled function because the size/dimensions aren't changing.
  • imagejpeg - Save the merged image.

Here's some untested code that loops through the array of tiles to create it. It uses constants for the width and height.

<?php
define('TILE_WIDTH', 40);
define('TILE_HEIGHT', 30);

$tiles = array(
    array('tile1.jpeg', 'tile2.jpeg'),
    array('tile3.jpeg', 'tile4.jpeg'),
);

$saveTo = 'result.jpeg';

$image = imagecreate(TILE_WIDTH * 2, TILE_HEIGHT * 2);
foreach($tiles as $row => $columns) {
    foreach($columns as $col => $filename) {
        $tile = imagecreatefromjpeg($filename);
        imagecopy($image, $tile, $row * TILE_WIDTH, $col * TILE_HEIGHT, 0, 0, TILE_WIDTH, TILE_HEIGHT);
    }
}

imagejpeg($image, $saveTo);

If you want to just display the image, you don't pass the second argument to imagejpeg, but you need to set the header content-type to image/jpeg.

Jacob
  • 8,278
  • 1
  • 23
  • 29
  • "Copy a portion of the existing image into a tile". So how do you add another image into existing title? – user622378 Mar 11 '11 at 23:52
  • You need to use imagecopy to copy from the tile image resources created with imagecreatefromjpeg into the larger image resource created with imagecreate. – Jacob Mar 12 '11 at 00:06