Snippets - GD
Watermark an image - Anthony 14/6/2008
Watermark an image; if you want to simply add text to an image check out the link below.
<?php// Create the canvas$canvas = imagecreate( 200, 100 );// Set the colours to use$black = imagecolorallocate( $canvas, 0, 0, 0 );$white = imagecolorallocate( $canvas, 255, 255, 255 );// Create a rectangle 200 x 100 and fill it whiteimagefilledrectangle( $canvas, 0, 0, 200, 100, $white );// Set the path to the font to use$font = "../fonts/verdana.ttf";// Set the text to use$text = "Sunflower";// Set the font size$size = "30";// Set the angle to rotate the font// In this case the font was not rotated - I must need savin to a tempory image and rotating$degrees = "30";// Set the image to watermark$photo= "../original_images/sunflower.jpg";// Find teh size of a bounding box for the text// If php has not been setup with the correct ttf support this will not work$box = imagettfbbox( $size, 0, $font, $text );// Find the value to use for the position in x - placing central on the image$x = (200 - ($box[2] - $box[0])) / 2;// Setup the position for the y$y = (100 - ($box[1] - $box[7])) / 2;$y -= $box[7];// Create the box with the textimageTTFText( $canvas, $size, 0, $x, $y, $black, $font, $text );// Change the white to transparentimagecolortransparent ( $canvas, $white );// Rotate the text - didn't workimagerotate( $canvas, $degrees, 0);// Save the tempory imageimagepng( $canvas, "temp.png" );// Clear the image from the memoryImageDestroy( $canvas );// Start a new image$watermark = imagecreatefrompng('temp.png');// Setup the image width and height$watermark_width = imagesx( $watermark );$watermark_height = imagesy( $watermark );$image = imagecreatetruecolor( $watermark_width, $watermark_height );$image = imagecreatefromjpeg( $photo );// Get the size of the photo to be watermarked$size = getimagesize( $photo );// Calculate the position of the watermark$dest_x = $size[0] - $watermark_width - 100;$dest_y = $size[1] - $watermark_height - 200;// Put the watermark onto the photoimagecopymerge( $image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, 50 );// Save the watermarked photoimagejpeg( $image, 'watermark_GD.jpg' );// Clear the images from the memoryimagedestroy( $image );imagedestroy( $watermark );// Delete the tempory imageunlink( 'temp.png');?>
