Development

Creating an image in PHP

You can do a lot with PHP and creating an image is one of them. You can add text or even other images onto your base image, here is how:

function create_image($width, $height, $text)
{
        $image = ImageCreate($width, $height);
        $white = ImageColorAllocate($image, 255, 255, 255);//white
        $grey = imagecolorallocate($im, 128, 128, 128);//grey
        $black = imagecolorallocate($im, 0, 0, 0);//black
        ImageFill($image, 0, 0, $white);
        $font = 'fonts/arial.ttf';//make sure chosen font is in the directory!!
        imagettftext($image, 20, 0, 4, 5, $grey, $font, $text);//text shadow
        imagettftext($image, 20, 0, 3, 4, $black, $font, $text);//text
        $save = "phpimage.png";//image will be save in this files directory as "phpimage.png"
        imagepng($image, $save);
        return $save;
        ImageDestroy($image);//Free memory
}

echo create_image(600, 200, 'Sample text for image');


The function create_image will create a white background image with your defined dimensions. It will then add your text and add text shadows then saving the image into the directory. Please not this method has a ‘custom’ font defined and you must have arial.ttf in the fonts folder in your directory for this script to work.

To add an image:

$picture = 'logo.png';
imagecopy($image, $picture, 55, 70, 0, 0, 48, 48);

For more understanding search: imagettftext and imagecopy.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago