Images from Tiles (GD)
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?
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.
精彩评论