Solved

PHP htaccess Watermark Resizing

Posted on 2012-03-28
1
752 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 110

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

Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Bootstrap - BootBox - PHP - MYSQL - Response Trigger 6 62
How ldap located a Domain controller? 22 78
Bash script to include windows servers 13 41
Conditional Array Element 7 28
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Google Drive is extremely cheap offsite storage, and it's even possible to get extra storage for free for two years.  You can use the free account 15GB, and if you have an Android device..when you install Google Drive for the first time it will give…
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…
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial

751 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