Solved

PHP htaccess Watermark Resizing

Posted on 2012-03-28
1
737 Views
Last Modified: 2012-04-29
I have a PHP script which places a watermark on images on my site.  How would I modify the below script to make it so the size of the watermark depends on the size of the image it's being placed on?  It'd be great if the height of the watermark could be 10% of the height of the image that it's being placed on.

Here's my code:

<?php
    
    /*
     * This script places a watermark on a given jpeg, png or gif image.
     */
    
      // loads a png, jpeg or gif image from the given file name
      function imagecreatefromfile($image_path) {
        // retrieve the type of the provided image file
        list($width, $height, $image_type) = getimagesize($image_path);
    
        // select the appropriate imagecreatefrom* function based on the determined
        // image type
        switch ($image_type)
        {
          case IMAGETYPE_GIF: return imagecreatefromgif($image_path); break;
          case IMAGETYPE_JPEG: return imagecreatefromjpeg($image_path); break;
          case IMAGETYPE_PNG: return imagecreatefrompng($image_path); break;
          default: return ''; break;
        }
      }
    
      // load source image to memory
      $image = imagecreatefromfile($_GET['image']);
      if (!$image) die('Unable to open image');
    
      // load watermark to memory
      $watermark = imagecreatefromfile($_GET['watermark']);
      if (!$image) die('Unable to open watermark');
    
      // calculate the position of the watermark in the output image (the
      // watermark shall be placed in the lower right corner)
      $watermark_pos_x = imagesx($image) - imagesx($watermark);
      $watermark_pos_y = imagesy($image) - imagesy($watermark);
    
      // merge the source image and the watermark
      imagecopy($image, $watermark,  $watermark_pos_x, $watermark_pos_y, 0, 0,
        imagesx($watermark), imagesy($watermark));
    
      // output watermarked image to browser
      header('Content-Type: image/jpeg');
      imagejpeg($image, '', 85);  // use best image quality (100)
    
      // remove the images from memory
      imagedestroy($image);
      imagedestroy($watermark);
    
    ?>

Open in new window


Not sure if this matters but here's my .htaccess code:
RewriteEngine on
    RewriteRule ^(.*\.(jp?g))$ /videogames/watermark.php?image=$1&watermark=watermark.png [NC]

Open in new window


Thanks.
0
Comment
Question by:davideo7
1 Comment
 
LVL 109

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 37781166
I don't think I can write the code for you, but I can suggest a way to handle this.

1. Create your image resource and get the X-Y dimensions
2. Compute the 10% values for each of X and Y
3. Create a new transparent image resource of X-Y dimensions
4. Copy the watermark into the transparent image using the 10% values
5. Copy the transparent image over the image resource and render the image

This code snippet shows how to write watermark information onto an image resource.  I use it with jQuery to create the fading image titles used on http://www.LandonBaseball.com

A slightly modified version of this script can be seen here (black is transparent):
http://www.landonbaseball.com/RAY_temp_banner.php?q=2012-banners/Thinkin_Baseball.jpg
<?php // LandonBaseball.com/banner.php

// WRITES A WATERMARK OVER THE BANNERS BACKGROUND AREA.
// USED WITH JQUERY TO FADE THE IMAGE BASENAME OUT

require_once('common.php');

// GET THE FULL PATH TO THE BANNER
$banner_url = (isset($_GET['q'])) ? $_GET['q'] : NULL;
if (!$banner_url) die();

// GET THE BANNER TEXT SIZE
$banner_size = (isset($_GET['s'])) ? $_GET['s'] : 24;

// GET THE TEXT FROM THE BANNER NAME
$banner_title = basename($banner_url);
$banner_title = preg_replace('#_+#',      ' ',  $banner_title);
$banner_title = preg_replace('#\.jpg$#i', NULL, $banner_title);
$banner_title = preg_replace('#^X\-#',    NULL, $banner_title);

// LOCATE THE FONT (VERDANA Z = BOLD ITALIC)
$font = 'fonts/verdanaz.ttf';

// PREPARE HORIZONTAL TEXT
$angle = 0;

// GET THE BOUNDING BOX SIZE FOR THE TEXT (DOES NOT INCLUDE DESCENDERS)
$poz = imageTTFBBox
( $banner_size           // SIZE IN POINTS
, $angle                 // ONLY WORKS RIGHT IF ANGLE = 0
, $font                  // PATH TO TTF FILE
, $banner_title          // TEXT
)
;

// GET THE WIDTH AND HEIGHT OF THE WATERMARK IMAGE WITH ROOM FOR DESCENDERS
$wmi_w = $poz[2] - $poz[0] + $banner_size;
$wmi_h = $poz[1] - $poz[7] + $banner_size;

// CREATE A TRUE COLOR WATERMARK IMAGE
$wmi = imageCreateTrueColor($wmi_w, $wmi_h);

// MAKE THE BACKGROUND
$wmi_bgc = imageColorAllocate($wmi,  85,   51,   0);
imageFill($wmi, 0, 0, $wmi_bgc);

// SET TEXT AND SHADOW COLORS
$wmi_txt = imageColorAllocate($wmi, 224,  224, 224);
$wmi_sh1 = imageColorAllocate($wmi, 128,  128, 128);
$wmi_sh2 = imageColorAllocate($wmi,  96,   96,  96);
$wmi_sh3 = imageColorAllocate($wmi,  80,   80,  80);

// SET SOME PADDING VALUES
$off_x = 6;
$off_y = (int)( $banner_size / 2 ) + ( $off_x / 2);

// SHADOW THE NAME ON THE WATERMARK IMAGE
imageTTFText
( $wmi                   // IMAGE RESOURCE
, $banner_size           // SIZE
, $angle                 // ANGLE
, $off_x + 3             // HORIZONTAL LEFTMOST BASEPOINT
, $wmi_h - $off_y + 3    // VERTICAL BASEPOINT
, $wmi_sh3               // COLOR INDEX
, $font                  // PATH TO TTF FILE
, $banner_title          // TEXT
)
;

// SHADOW THE NAME ON THE WATERMARK IMAGE
imageTTFText
( $wmi                   // IMAGE RESOURCE
, $banner_size           // SIZE
, $angle                 // ANGLE
, $off_x + 2             // HORIZONTAL LEFTMOST BASEPOINT
, $wmi_h - $off_y + 2    // VERTICAL BASEPOINT
, $wmi_sh2               // COLOR INDEX
, $font                  // PATH TO TTF FILE
, $banner_title          // TEXT
)
;

// SHADOW THE NAME ON THE WATERMARK IMAGE
imageTTFText
( $wmi                   // IMAGE RESOURCE
, $banner_size           // SIZE
, $angle                 // ANGLE
, $off_x + 1             // HORIZONTAL LEFTMOST BASEPOINT
, $wmi_h - $off_y + 1    // VERTICAL BASEPOINT
, $wmi_sh1               // COLOR INDEX
, $font                  // PATH TO TTF FILE
, $banner_title          // TEXT
)
;

// WRITE THE NAME ON THE WATERMARK IMAGE
imageTTFText
( $wmi                   // IMAGE RESOURCE
, $banner_size           // SIZE
, $angle                 // ANGLE
, $off_x + 0             // HORIZONTAL LEFTMOST BASEPOINT
, $wmi_h - $off_y + 0    // VERTICAL BASEPOINT
, $wmi_txt               // COLOR INDEX
, $font                  // PATH TO TTF FILE
, $banner_title          // TEXT
)
;

// GET OVERALL IMAGE DIMENSIONS
list($w, $h) = getImageSize($banner_url);

// CREATE A TRUE COLOR TRANSPARENT IMAGE
$out = imageCreateTrueColor($w, $h);
$out_bgc = imageColorAllocate($out,  0,0,0);
imageFill($out, 0, 0, $out_bgc);
imageColorTransparent($out, $out_bgc);

// PUT THE WATERMARK ON THE BOTTOM LEFT
imageCopy
( $out         // DESTINATION
, $wmi         // SOURCE (WATERMARK)
, 0            // DESTINATION X-AXIS IN PIXELS
, $h - $wmi_h  // DESTINATION Y-AXIS IN PIXELS
, 0            // SOURCE X-AXIS IN PIXELS
, 0            // SOURCE Y-AXIS IN PIXELS
, $wmi_w       // SOURCE WIDTH
, $wmi_h       // SOURCE HEIGHT
)
;

// RENDER THE IMAGES AND RELEASE THE MEMORY
imagePNG($out);
imageDestroy($wmi);
imageDestroy($out);

Open in new window

0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It’s 2016. Password authentication should be dead — or at least close to dying. But, unfortunately, it has not traversed Quagga stage yet. Using password authentication is like laundering hotel guest linens with a washboard — it’s Passé.
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
The viewer will learn how to count occurrences of each item in an array.
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…

776 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