Image Manipulation : Watermark images on the fly through PHP and GD

by Koree S. Monteloyola

 

Let's say you're given a hundred "digital" images and you need to put watermarks on each of those photos.

If you're going to do this manually, man! It would eat a lot of your time.

So here's a solution: a php script that would automatically merge a watermark to an image.

Requirements:

  • PHP 4+
  • GD 2.0+ Library
  • watermark file should be saved as PNG-8, not PNG-24.


<?php
$err=0;
if(empty($_GET['path'])){
    $path = 'images/wrongPath.gif';
    $err++;
}else{
    if(!is_file(getcwd().'/images/'.$_GET['path'])){
        $path = 'images/wrongPath.gif';
    }else{
        $path = 'images/'.$_GET['path'];
    }
}
$srcImage = $path;
header("Content-type: " . image_type_to_mime_type(exif_imagetype($srcImage)));
switch(exif_imagetype($srcImage)){
    case IMAGETYPE_GIF:
        $image = imagecreatefromgif($srcImage);
        break;
    case IMAGETYPE_JPEG:
        $image = imagecreatefromjpeg($srcImage);
        break;
    case IMAGETYPE_PNG:
        $image = imagecreatefrompng($srcImage);
        break;
}
if(empty($err)){
    $watermark = imagecreatefrompng(getcwd().'/images/watermark.png');
    $watermark_width = imagesx($watermark);
    $watermark_height = imagesy($watermark);
    $size = getimagesize($srcImage);
    $dest_x = $size[0] - $watermark_width - 10;
    $dest_y = $size[1] -$watermark_height - 10;
    imagecopymerge($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, 100);
}
switch(exif_imagetype($srcImage)){
    case IMAGETYPE_GIF:
        imagegif($image);
        break;
    case IMAGETYPE_JPEG:
        imagejpeg($image);
        break;
    case IMAGETYPE_PNG:
        imagepng($image);
        break;
}
imagedestroy($image);
imagedestroy($watermark);
?>


You can download a sample of the script here.

blog comments powered by Disqus