Hack32.Create Image Overlays


Hack 32. Create Image Overlays

Using PHP's graphics capabilities to build a single image from several source images.

One common graphics scenario is to put some overlay images at specific data-driven locations, stacking those overlays on top of another base graphic. This hack starts with the map in Figure 4-10 as the base image.

Figure 4-10. The map graphic


Then it places the star graphic in Figure 4-11 onto the map, over the city of San Francisco, as it might appear if you were looking up a location by city or Zip code.

Figure 4-11. The star graphic


4.7.1. The Code

Save the (rather simple) code in Example 4-8 as graphic.php.

Example 4-8. PHP making overlaying graphics almost trivial
 <?php $map = imagecreatefrompng("map.png"); $star = imagecreatefromgif("star.gif"); imagecopy( $map, $star, 5, 180, 0, 0, imagesx( $star ), imagesy( $star ) ); header("Content-type: image/png"); imagepng($map); ?> 

The code starts by reading in the map and star graphics. Then it creates a new image, superimposing the star onto the map using the imagecopy() function. The new version of the mapwhich at this point exists only in memoryis then output to the browser using the imagepng() function.

4.7.2. Running the Hack

After uploading the PHP script and the images to your server, navigate your browser to graphic.php. There you will see an image like that shown in Figure 4-12.

Figure 4-12. The star graphic overlaid on the map graphic


4.7.3. Hacking the Hack

The star on the map is cool, but it's a bit big. Instead of sitting on top of San Francisco, it ends up sitting on top of most of California. Let's scale it down a little. Save the code in Example 4-9 as graphic2.php.

Example 4-9. A little bit of scaling
 <? $map = imagecreatefrompng("map.png"); $star = imagecreatefromgif("star.gif"); imagecopyresized( $map, $star, 25, 205, 0, 0, imagesx( $star )/5, imagesy( $star )/5, imagesx( $star ), imagesy( $star ) ); header("Content-type: image/png"); imagepng($map); ?> 

Then navigate to the new script in your web browser; you shouldsee the graphic shown in Figure 4-13.

Figure 4-13. The map overlaid with a scaled version of the star graphic


This new version of the script uses the imagecopyresized() function to change the size of the star image as it's copied onto the map. The script divides the star's width and height by 5, scaling the image to 20% of its original size.

Because the star is a pixilated graphic, if you make the image larger than the original, you'll start to see some jagged edges.


4.7.4. See Also

  • "Create Thumbnail Images" [Hack #27]

  • "Access Your iPhoto Pictures with PHP" [Hack #33]

  • "Split One Image into Multiple Images" [Hack #30]



PHP Hacks
PHP Hacks: Tips & Tools For Creating Dynamic Websites
ISBN: 0596101392
EAN: 2147483647
Year: 2006
Pages: 163

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net