Watermark your images with PHP on the fly

Visited 4952 times | Submited on 2007-04-18 15:30:09

Commands we will use:

header()
imagefrompng()
imagefromjpeg()
imagecopymerge()
imagejpeg()
imagedestroy()
getimagesize()

The method:

1. send your browser an image header, because you will create a new image:

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

2. get your watermark image, and the other image what your want to get watermarked too:

$wm = imagecreatefrompng("watermark.png");
$img = imagecreatefromjpeg("myimage.jpg");

4. if you want to center your watermark on your image, you should calculate it's position:

$wmsize = getimagesize("watermark.png");
$imgsize = getimagesize("myimage.jpg");
$destx = ($imgsize[0] - $wmsize[0]) / 2;
$desty = ($imgsize[1] - $wmsize[1]) / 2;

3.use the imagecopymerge() function to copy your watermark to your image:

imagecopymerge($img,$wm,$destx,$desty, 0, 0, $wmsize[0], $wmsize[1], 75);

- the last parameter of the above function is the alpha transparency

4. send the new image to the browser:

imagejpeg($img);

5. finally, destroy your sources:

imagedestroy($img);
imagejpeg($img);

The full source:

<?php
header("content-type: image/jpeg");
$wm = imagecreatefrompng("watermark.png");
$img = imagecreatefromjpeg("myimage.jpg");
$wmsize = getimagesize("watermark.png");
$imgsize = getimagesize("myimage.jpg");
$destx = ($imgsize[0] - $wmsize[0]) / 2;
$desty = ($imgsize[1] - $wmsize[1] / 2;
imagecopymerge($img,$wm,$destx,$desty, 0, 0, $wmsize[0], $wmsize[1], 75);
imagejpeg($img);
imagedestroy($img);
imagedestroy($wm);
?>

By Peter Radics web design - cleanweb.hu



Comments (5)

  • On September 15, 2007 07:57 Doesn't matter said:

    The shortest and greatest watermark script on the net..
    Greate work, thanks 4 share

  • On October 20, 2007 16:54 Jimmy said:

    very good.

  • On January 05, 2008 17:00 Athul said:

    Excellent ! Thank You

  • On March 12, 2008 00:04 Dennis said:

    Does not work with transparent PNG with shadows

  • On August 15, 2008 03:07 Mahmoud M. Abdel-Fattah said:

    It'll be much better, if u use imagecopy() Instead of imagecopymerge()

Add your comment

Name:(required)
E-mail address:(optional)
Comment:(required)
Repeat the number for validation: (required)

Browse by Tags:


Related Articles:

Text Link Ads

Statistics

Total 296 articles submitted
Latest submission at January 28, 2008 15:13

Feedback

Use this email below to send us your suggestions and feedback. We value your opinion.
info (at) theitarticles.com