Add a text watermark to an image with PHP

June 28, 2014 | 2594 views | Comments

Dynamically add a custom text to an image as it's watermark using PHP with the function imagestring().

For example.

Reference Tutorial: Create an image with custom text in PHP

//the image to be watermarked
$image = 'images/create-a-lonely-child-scene-photo-manipulation.jpg';

/*
 * set the watermark font size
 * possible values 1,2,3,4, and 5
 * where 5 is the biggest
 */
$fontSize = 4;

//set the watermark text
$text = "ConsistentCoder.com";

/*
 * position the watermark
 * 10 pixels from the left
 * and 10 pixels from the top
 */
$xPosition = 10;
$yPosition = 10;

//create a new image
$newImg = imagecreatefromjpeg($image);

//set the watermark font color to red
$fontColor = imagecolorallocate($newImg, 255, 0, 0);

//write the watermark on the created image
imagestring($newImg, $fontSize, $xPosition, $yPosition, $text, $fontColor);

//output the new image with a watermark to a file
//imagejpeg($newImg,"add-a-text-watermark-to-an-image-with-php_01.jpg",100);
/*
 * PNG file appeared to have
 * a better quality than the JPG
 */
imagepng($newImg,"add-a-text-watermark-to-an-image-with-php_01.png");

/*
 * destroy the image to free
 * any memory associated with it
 */
imagedestroy($newImg);

Result.

PNG

Please mouse over here to view the image.

Result.

JPG (100% quality)

Please mouse over here to view the image.

Other options:

Center the watermark on the image.

Put the watermark on the lower right corner of the image.

To place the watermark on the upper right corner of the image.

 

Sample image courtesy of CienelDotNet : Create A Lonely Child Scene Photo Manipulation (used with permission).