22 January 2009

Function to create Watermark on Image

function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile, $hheight=0, $wwidth=0) {
list($width, $height) = getimagesize($SourceFile);
$image_p = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($image_p, 255, 255, 255);
imagefill($image_p, 0, 0, $white);
$image = imagecreatefromjpeg($SourceFile);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);
$black = imagecolorallocatealpha($image_p, 255, 255, 255, 100);

$font = 'arial.ttf';
$font_size = 20;
imagettftext($image_p, $font_size, 0, 0, 30, $white, $font, $WaterMarkText);
//imagettftext($image_p, $font_size, 0, 10, 20, $black, $font, $WaterMarkText);
if ($DestinationFile<>'') {
imagejpeg ($image_p, $DestinationFile, 100);
} else {
header('Content-Type: image/jpeg');
imagejpeg($image_p, null, 100);
};
imagedestroy($image);
imagedestroy($image_p);
}

1 comment:

Alex said...

Hi. I was trying to address the issue of the colour of the watermark text when you can't readily tell what colour the background will be. There's no point in writing black text on a black background, so I came up with the following function to determine the background colour where the text will be, and find a text colour value on that basis that ensures the text will be visible:


function get_cols_invert($im)
{
//$im is the same as $SourceFile for the watermarkimage function

$im = imagecreatefromjpeg($im); //get the images
$cols = range(20, 120, 10); //20, 120 and
$rows = range(30, 60, 10); // 30, 60 are the co-ords roughly where the text will be. Increment 10 as every pixel is a waste.
$array_cols = array();
foreach ($cols as $col)
{
foreach ($rows as $row)
{
$c++;
}
} //gives us total number of colour points tested.

foreach ($cols as $col)
{
foreach ($rows as $row)
{
//gets pixel color at co-ords
$rgb = imagecolorat($im, $col, $row);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF; //get the values
$allr = $allr + $r; //sums up the values
$allg = $allg + $g;
$allb = $allb + $b;
}
}
imagedestroy($im); //we've finished with the image
$avgr = round($allr/$c); //the average r colour
$avgg = round($allg/$c); //and so on
$avgb = round($allb/$c);
if ($avgr >= 140) {$newr = $avgr/4;} else {$newr = $avgr*4;} if ($newr > 255) {$newr = 250;}
if ($avgg >= 140) {$newg = $avgg/4;} else {$newg = $avgr*4;} if ($newg > 255) {$newg = 250;}
if ($avgb >= 140) {$newb = $avgb/4;} else {$newb = $avgr*4;} if ($newb > 255) {$newb = 250;}

//above, adjust the new colours so they are visible.
$newr = round($newr);
$newg = round($newg);
$newb = round($newb);

return array($newr, $newg, $newb);
}


So to use in watermarkimage, you call the function

$colours = get_cols_invert($SourceFile);

and in the function, you change the line to the right colours, e.g.

$black = imagecolorallocate($image_p, $colours[0], $colours[1], $colours[2]);

Bingo.

Being used on my black dating site and filipina dating site.