Adding a watermark with PHP

Posted on 2005-05-16
Last Modified: 2012-06-21
Below is the code I'm trying to use to firstly resize my image and then add a watermark to it..but i just can't get it to work. Any help would be greatly appreciated.

$cfg_fullsizepics_path = "../images/magazine/$edition/articles/$id/main";
$cfg_thumb_path = "../images/magazine/$edition/articles/$id/main";
$filepath = "../images/magazine/$edition/articles/$id/main";
$dir = dir($filepath);
while($entry=$dir->read()) {
    if($entry == "." || $entry == "..") {
    $fp = @fopen("$filepath/$entry","r");
    $new_w = 800;
$image_stats = GetImageSize($cfg_fullsizepics_path."/".$entry);
$imagewidth = $image_stats[0];
$imageheight = $image_stats[1];
$img_type = $image_stats[2];
$ratio = ($imagewidth / $new_w);
$new_h = round($imageheight / $ratio);
$filename = $entry;
 Define('WATERMARK_IMAGE', './wt.png'); // path to watermark image
 Define('WATERMARK_PERCENT', '70'); // Intensity of the transition (in percent)
 Define('WATERMARK_ALIGN_H', 'right'); // left / right / center
 Define('WATERMARK_ALIGN_V', 'bottom'); // top / bottom / center
 Define('WATERMARK_MARGIN', '10'); // margin
 if ($img_type=="2") {
  if ($wt_image) {

   if (WATERMARK_ALIGN_V=='top') {
   } elseif (WATERMARK_ALIGN_V=='bottom') {
   } elseif (WATERMARK_ALIGN_V=='center') {

   if (WATERMARK_ALIGN_H=='left') {
   } elseif (WATERMARK_ALIGN_H=='right') {
   } elseif (WATERMARK_ALIGN_H=='center') {
      $src_img = imagecreatefromjpeg($cfg_fullsizepics_path."/".$entry);
      $dst_img = imagecreatetruecolor($new_w,$new_h);
      $tmp = imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesx($src_img),imagesy($src_img));
      imagecopymerge($tmp, $wt_image, $wt_x, $wt_y, 0, 0, $image2_width, $image2_height, WATERMARK_PERCENT);
imagejpeg($dst_img, "$cfg_thumb_path"."/$entry");
Question by:spikeyjames

    Expert Comment

    I do this for an application I have... the solution is pretty easy once you get it figured out.  My code is a bit different than yours but you should be able to get the information you need from it without much problem.


    //The tmp file -- file that will have the composite of both images
    $tmpFile = $tempSavePath;

    //The image to use as the watermark
    $watermarkFile = "/watermark/watermark.jpg";
    //add the watermark to the image if there has been a watermark selected
        $waterDimen = getImageSize($watermarkFile);
        //The image that we want to add the watermark to
        $destinationFile = $tempSavePath;
        $rawDimen = getImageSize($destinationFile);
        //Place the watermark 5 pixels away from the right hand side of image
        $placement_x = $rawDimen[0]-$waterDimen[0]-5;
        //Place the watermark 5 pixels away from the bottom of image
        $placement_y = $rawDimen[1]-$waterDimen[1]-5;
        //The path to the imagemagick composite program.
        $composite = "{$imagemagickdir}/composite";
        //Create and execute the command to create the watermark file (saves to the $tmpFile)
        $cmd = "$composite -watermark 13.0 -geometry +$placement_x+$placement_y $watermarkFile $destinationFile $tmpFile";

    //Resize the image to the most common 2 sizes, plus a 'full' size for later copying and using
    $command = "{$imagemagickdir}/convert -size 800x600 '{$tempSavePath}' -resize 800x600 +profile \"*\" '{$final_savePath}/{$productId}.jpg'";

    Expert Comment

    ignore the comment saying:
    //Resize the image to the most common 2 sizes, plus a 'full' size for later copying and using

    it should say:
    //Resize the image to a standard 800x600 size
    LVL 1

    Author Comment

    Is there any chance you could just tell me what is wrong with my code? because I'm not that good with PHP, and I can't see from that what I've done wrong. Also, what is imagemagick? That is not in my script at it needed?


    Expert Comment

    here is an example much closer to yours (found in a file i will call 'image.php').  you call it from another page like this: <img src="image.php">

    Here's the code:

    //Get the original image size
    list($width_orig, $height_orig) = getimagesize($imagePath);

    //Set the desired height
    $width = $globalInfo->GetOneSizeImageWidth($portrait);
    $height = $globalInfo->GetOneSizeImageHeight($portrait);

    //using the two sets of sizes from above, get the new photo size
    if ($width && ($width_orig < $height_orig))
      $width = ($height / $height_orig) * $width_orig;
      $height = ($width / $width_orig) * $height_orig;

    // Resample the image to the size wanted
    $image_p = imagecreatetruecolor($width, $height);
    $image = imagecreatefromjpeg($imagePath);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

    //Get the watermark file in a usable format
    $watermark = imagecreatefromgif('images/copyright_portrait.gif');  

    //Get the size of the watermark image
    $watermark_width = imagesx($watermark);  
    $watermark_height = imagesy($watermark);  

    //get the x and y locations for where you want to put the watermark (change this to whatever you'd like)
    $dest_x = ($width - $watermark_width);
    $dest_y = ($height - $watermark_height);
    imagecopymerge($image_p, $watermark, 0, $dest_y, 0, 0, $watermark_width, $watermark_height, 25);  

    //display the image

    //destroy the two temporary images
    LVL 14

    Expert Comment

    No comment has been added to this question in more than 21 days, so it is now classified as abandoned.
    I will leave the following recommendation for this question in the Cleanup topic area:
    Accept: Caliguian

    Any objections should be posted here in the next 4 days. After that time, the question will be closed.

    EE Cleanup Volunteer
    LVL 1

    Author Comment

    No, I wanted to resize the image when it was uploaded to the server, not when it was downloaded from the server - that response didn't answer my question.

    Accepted Solution

    That code works for both uploading and displaying.  The only difference you would have for image you wanted to save instead of display is change the line:



    imagejpeg($image_p, 'wherever/you/want/to/put/the');  

    Looks like you didn't even try it.  But whatever.
    LVL 10

    Expert Comment

    I agree with Caliguian, if this had of been followed up the question would have been answered.

    My 2 cents :)
    LVL 1

    Author Comment

    You're right. I moved on to more important matters and left this aside. Happy to offer what little points I have left, as you did eventially answer the question :P


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Highfive Gives IT Their Time Back

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
    Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
    The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

    760 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    11 Experts available now in Live!

    Get 1:1 Help Now