Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to set the tile image for filling using imagesettile() function in PHP?
The imagesettile() function is an inbuilt function in PHP that sets the tile image for filling operations. It defines the image to be used by all-region filling functions like imagefill() and imagefilledpolygon() when filling with the special color IMG_COLOR_TILED.
A tile is an image that fills an area with a repeated pattern. Any GD image resource can be used as a tile to create seamless patterns across larger areas.
Syntax
bool imagesettile($image, $tile)
Parameters
imagesettile() accepts two parameters −
$image − The image resource (canvas) where the tile will be applied
$tile − The image resource that will be used as the repeating tile pattern
Return Value
Returns true on success or false on failure.
Example 1 − Basic Tile Pattern
Note: This example requires the GD extension and image files. Ensure you have a PNG image available for testing.
<?php
// Load a PNG image to use as tile
$tileImage = imagecreatefrompng('/path/to/your/tile.png');
// Create a canvas of 700x300 pixels
$canvas = imagecreatetruecolor(700, 300);
// Set the tile image for filling operations
imagesettile($canvas, $tileImage);
// Fill a rectangle using the tiled pattern
imagefilledrectangle($canvas, 0, 0, 700, 300, IMG_COLOR_TILED);
// Output the image
header('Content-Type: image/png');
imagepng($canvas);
// Clean up memory
imagedestroy($canvas);
imagedestroy($tileImage);
?>
Example 2 − Creating Pattern with Custom Tile
<?php
// Create a simple tile pattern (20x20 red square with white border)
$tile = imagecreatetruecolor(20, 20);
$red = imagecolorallocate($tile, 255, 0, 0);
$white = imagecolorallocate($tile, 255, 255, 255);
// Fill tile with red and add white border
imagefill($tile, 0, 0, $red);
imagerectangle($tile, 0, 0, 19, 19, $white);
// Create main canvas
$canvas = imagecreatetruecolor(400, 200);
// Apply the custom tile
imagesettile($canvas, $tile);
// Fill the entire canvas with tiled pattern
imagefill($canvas, 0, 0, IMG_COLOR_TILED);
// Output the result
header('Content-Type: image/png');
imagepng($canvas);
// Cleanup
imagedestroy($canvas);
imagedestroy($tile);
?>
Key Points
Use
IMG_COLOR_TILEDas the color parameter in filling functions to apply the tileThe tile image will repeat seamlessly across the filled area
Both the canvas and tile must be valid GD image resources
Always destroy image resources to free memory after use
Conclusion
The imagesettile() function provides an efficient way to create repeating patterns in PHP image manipulation. It's particularly useful for backgrounds, textures, and decorative fills in dynamically generated images.
