umbbberto
umbbberto

Reputation: 61

add a watermark on images

I trying to add a watermark, a png with transparent background, on images (jpg/gif/png/jpeg)...I have 2 files...the first one is watermark.php:

<?php
    require 'func/images.func.php';
    if (isset($_FILES['image'])){
         $file_name =       $_FILES['image']['name']; 
         $file_tmp =        $_FILES['image']['tmp_name'];   
         $name = explode('.', $file_name);
         if (allowed_image($file_name) === true){
            $file_name = $img_name .'.png';
            watermark_image($file_tmp, 'images-watermark/uploads/' . $file_name);       
         } else{
          echo '<p>no image, or image type not accepted.</p>';
         }
     }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Documento senza titolo</title>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
Choose an image:
<input type="file" name="image" />
<input type="submit" value="watermark"/>
</form>
</body>
</html>

...and the second one is images.func.php:

<?php
    function allowed_image($file_name){
    $allow_set = array('jpg', 'jpeg', 'gif', 'png');
    $file_ext =   (explode('.', $file_name));
    $end = end($file_ext);  
    return (in_array($end , $allow_set) === true) ? true : false;   
}

function watermark_image($file, $destination){
    $watermark = imagecreatefrompng('images-watermark/watermarkf.png'); 
    $source = getimagesize($file);  
    $source_mime = $source['mime']; 
    if ($source_mime === 'image/png'){
        $image = imagecreatefrompng($file);     
    }else if($source_mime === 'image/jpeg'){
        $image = imagecreatefromjpeg($file);    
    }else if($source_mime === 'image/gif'){
        $image = imagecreatefromgif($file);         
    }   
    imagecopy($image, $watermark, 70, 160, 0, 0, imagesx($watermark),imagesy($watermark));  
    imagepng($image, $destination); 
    imagedestroy($image); 
        imagedestroy($watermark);

}
?>

...my code works with jpg/png/jpeg format (the images have a watermark with transparent background)...in gif images the watermark has not a transparent background...any tips? thanks in advance

Upvotes: 0

Views: 1017

Answers (2)

SoniCoder
SoniCoder

Reputation: 4174

I would recommend using a library for this if You don't do it for experimental purpose. My personal favorite is PHP Image Workshop or You can use Imagine also.

Upvotes: 1

GIF images need to be unpacked to full RGB, then mixed, then reindexed to 256 colors. Adding a transparent watermark on top of an image is a great way to make the data impossible to capture in GIF form because you introduced 256 new shades of overlay.

Upvotes: 1

Related Questions