Basic PHP Image Watermark With GD Library

February 1st, 2011 by aditia rahman / 3 Comments  


For today just wanna go back to a little PHP code again, I want share to creating a very basic image watermarking in PHP, watermark  feature are already widely used in some popular digital art, and photo websites like istockphotos, deviantart and any other sites, that maybe I don’t even know. Now here it goes, first make sure you have GD installed with PHP, you can check on your default phpinfo page using <?php phpinfo(); ?>, or you can use this php script

if (!function_exists("gd_info")) {
	echo "GD not installed";
} else {
	echo "GD installed";

Text Watermark

Now let’s get straight to the code, the first way to adding watermarking is by add text which called true type font on the server, you can freely choose the font you want to use and it will be better to include the font file in the server.


header("Content-type: image/jpeg");

// get image file
$img_name = "batman.jpg";
$img_src = imagecreatefromjpeg($img_name);
$width_src = imagesx($img_src);
$height_src = imagesy($img_src);

// new image size = old image size
$width_dst = $width_src;
$height_dst = $height_src;
$quality = 80;

// create new image
$img = imagecreatetruecolor($width_src, $height_dst);
imagecopyresampled($img, $img_src, 0, 0, 0, 0, $width_dst, $height_dst, $width_src, $height_src);

// rectangle size for text box
$x1_rect = 0;
$y1_rect = $height_dst - 18;
$x2_rect = $width_dst;
$y2_rect = $height_dst;

$color = imagecolorallocate($img, 0, 0, 0);
$letter_color = imagecolorallocate($img, 255, 255, 255);
$text = "scissormetimbers (";
imagefilledrectangle($img, $x1_rect, $y1_rect, $x2_rect, $y2_rect, $color);
imagettftext($img, 12, 0, $x1_rect+5, $y1_rect+14, $letter_color, "DroidSans.ttf", $text);

// show in browser
imagejpeg($img, '', $quality);


Image Watermark

If in someway you want to adding an image you can add this code, before the image showing in the browser, I think it is better to choose the image with the transparent background, for watermarking.

$logo = imagecreatefromgif("da.gif");
imagecopymerge($img, $logo, 200, 50, 0, 0, 300, 300, 80);

Here are the example result, using both text and image watermark

php watermark sample

Saving The File

To save the modified image modify this line of code

imagejpeg($img, '', $quality);


imagejpeg($img, 'new_image_name.jpg', $quality);
View Demo | Download Source

Credit Image: Batman
Font: Droid Sans

        submit to reddit Delicious

3 Comments Leave a Comment Subscribe RSS

Leave a Comment