Web Development

  Homes arrow Web Development arrow Beginning PHP4 : Generating Graphics Part 6 -...
 Webmaster Tools
Base64 Encoding 
Browser Settings 
CSS Coder 
CSS Navigation Menu 
Datetime Converter 
DHTML Tooltip 
Dig Utility 
DNS Utility 
Dropdown Menu 
Fetch Content 
Fetch Header 
Floating Layer 
htaccess Generator 
HTML Encoder 
HTML Entities 
IP Convert 
Meta Tags 
Password Encryption
Password Strength
Pattern Extractor 
Ping Utility 
Pop-Up Window 
Regex Extractor 
Regex Match 
Scrollbar Color 
Source Viewer 
Syntax Highlighting 
URL Encoding 
Web Safe Colors 
Forums Sitemap 
Weekly Newsletter
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Contact Us 
Site Map 
Privacy Policy 
  >>> SIGN UP!  
  Lost Password? 

Beginning PHP4 : Generating Graphics Part 6 - Advanced Graphics Manipulation
By: Developer Shed
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating:  stars stars stars stars stars / 0

    Table of Contents:

    Rate this Article: Poor Best 
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article




    Beginning PHP4 : Generating Graphics Part 6 - Advanced Graphics Manipulation
    by Wrox Books

    A Stylized Map

    For this example we're going to dynamically create a stylized map. The map of the area itself will already exist and we will use this as a starting point. We shall then create a series of separate images, each containing an icon that represents an attraction on our map. We can then combine the images to create a composite map, with icons highlighting any of the tourist attractions.

    The code that we use in this example will not be database driven, but will have the coordinates hard-coded into the script. You can easily combine the techniques we use here with the techniques we covered in the previous example if you wish to make a dynamic version of this map.

    Here's the map that we'll be dropping our icons onto:

    On top of this image we want to draw what appears to be a pin stuck into the map:

    We'll call these files island.jpg and pin.jpg respectively.

    Copies of these files are included in the code download for this book, available from http://www.wrox.com. Alternatively, you can use your own images and modify the following code accordingly.

    We simply open up both of our image files and use ImageCopyResized() to copy the pin into the map image, and place it where we want:

    Header("Content-type: image/jpeg");
    $image = ImageCreateFromJPEG("island.jpg");
    $icon = ImageCreateFromJPEG("pin.jpg");
    $width = ImageSX($icon);
    $height = ImageSY($icon);

    Note that we use three JPEG-specific functions here that are completely equivalent to the corresponding PNG functions we've used above. Only the names have been changed.

    Two more functions that we haven't seen before, ImageSX() and ImageSY() return the width and height of the specified image respectively. We then use these values as width and height values for source and destination images in ImageCopyResized().

    You'll notice straight away that there's a problem with the figure, as shown below. The white background of our pin image has been copied through as well as the pin itself, and has obscured part of the map.

    What we need to be able to do is to specify certain areas or colors of the image as being transparent. The function ImageColorTransparent() does just that, and takes 2 arguments: an image identifier and a color identifier. The specified color is then marked as transparent. However, there's a problem - in this case, we know that we want white to be the transparent color, and we know how to create white with ImageColorAllocate(); but what if the background was purple? How would we know exactly what values to use when defining $purple?

    It's actually quite simple: we use the ImageColorAt() function, which returns an image identifier for the color of a specific pixel in a specified image. ImageColorAt() requires an image identifier and x and y image coordinates for the pixel to use. We then use the returned color identifier to specify a transparent color in ImageColorTransparent():

    Header("Content-type: image/jpeg");
    $image = ImageCreateFromJPEG("island.jpg");
    $icon = ImageCreateFromJPEG("pin.jpg");
    $trans = ImageColorAt($icon, 0, 0);
    ImageColorTransparent($icon, $trans);
    $width = ImageSX($icon);
    $height = ImageSY($icon);

    Below is a portion of the result, which hasn't given us the results we expected:

    Only some parts of the white have been made transparent. If you open up pin.jpg and zoom in on a portion of the white part of the image, you'll notice that the white is not actually pure white, but a mixture of very light colors with subtle variations in their RGB values.

    The following piece of code uses a new function, ImageColorsForIndex() that returns to us an associative array of the red, green and blue components of a specified color. We can use this to highlight what our eyes can't necessarily detect:

    $image = ImageCreateFromJPEG("pin.jpg");
    echo "<table border=1>\n";
    for ($y=0;$y<4;$y++) {
    echo "<tr>\n";
    for ($x=0;$x<4;$x++) {
    $temp = ImageColorAt($image,$x,$y);
    $colorarray = ImageColorsForIndex($image,$temp);
    echo "<td>";
    echo "<font color=red>".$colorarray["red"]."</font><br>\n";
    echo "<font color=green>".$colorarray["green"]."</font><br>\n";
    echo "<font color=blue>".$colorarray["blue"]."</font><br>\n";
    echo "</td>\n";
    echo "</table>\n";

    This script creates a 4x4 table containing the RGB components of the corresponding 4pixel x 4pixel area in the top left-hand corner of our image. The resultant output:

    highlights the subtle differences between the pixels. In our previous example we were marking the very top left-hand pixel at 0,0 as the transparent color. In the 16 pixels we've chosen, only 3 others have the same RGB values as the top left-hand one.

    One of the options that we have open to us to remedy this situation is to save the JPEG at a very high quality; hopefully this will minimize color variation through the image. Another option is to use an indexed color image. An indexed color image is commonly used for putting images on the web or for multimedia output, and has 256 or fewer colors.

    One of the nicest features of an indexed color image is the ability to drop the number of colors in the image. This not only reduces the file size but (crucially for us) eliminates the variations in color that have so far foiled our attempts at making the area around our pin transparent.

    pin.png is simply a copy of pin.jpg in PNG format. It was converted by a graphics program and the number of colors in the image was reduced to 10. The only alterations we need to make are to modify the line that opens pin.jpg so that it opens pin.png instead, and exchange the function ImageCreateFromJPEG() for ImageCreateFromPNG():

    $icon = ImageCreateFromPNG("pin.png");

    The result is immediately apparent:

    Palette Limitations

    This is far better, but although the horrible white block has been removed from around the pin you may notice that the head of the pin is the wrong color. This is due to the relatively small number of colors available in the color table. As pixels are copied from one image to another, we can't use the same color indexes between images. Images may have different color tables and the color that we see on the screen for the index in the source image is not always the same color in the corresponding color index in the destination image.

    For this reason when we use the ImageCopyResized() function a number of things happen in the background. The first thing that happens is the ImageColorExact() function is used to try and find an exact RGB color match in the destination image. If no match is found, ImageColorAllocate() is used to try and allocate the color for the destination image. If this also fails the ImageColorClosest() function is used to find the closest approximate color in the destination image.

    Because our pin head is not appearing in the red that we would expect, we can assume that the ImageCopyResized() function has had to use the closest color that it could find. So why can it not allocate a nice, bright red in the destination image?

    If we turn to the documentation for the gd libraries themselves, we find that gdImageColorAllocate (as it's called in the library) will fail if all 256 colors have already been allocated.

    The following piece of code uses the ImageColorsTotal() function to display the number of colors in a given image's palette:

    $image = ImageCreateFromJPEG("island.jpg");
    echo ImageColorsTotal($image);

    This will return a value of 256, explaining why ImageColorAllocate() fails and resorts to the closest available color. The JPEG format itself is not restricted to 256 colors, but the current version of the gd libraries only supports this many colors in a single image palette.

    We saw earlier that with an indexed color image we could specify the number of colors in its palette. If we were to save our image of the island as a PNG file with 128 colors, we would have 128 colors available, and therefore not impact as heavily on the quality of the image:

    Header("Content-type: image/png");
    $image = ImageCreateFromPNG("island.png");
    $icon = ImageCreateFromPNG("pin.png");
    $trans = ImageColorAt($icon,0,0);
    $width = ImageSX($icon);
    $height = ImageSY($icon);


    During the course of this chapter we looked at how to create, open, manipulate and output images with PHP. This can enable you to add a new dimension to the scripts and web pages that you are already creating.

    We have seen how these tools can be used in a practical and meaningful way to add value to the content in a web site. Now, not only can it have good looking graphics, but those graphics can engage visitors to your site by making them relate directly to a topic that interests them.

    We have looked at some background information on graphics, and seen a little of their internal workings. Insight like this is essential if you want to really understand what's happening when you use the PHP's image functions.

    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More Web Development Articles
    More By Developer Shed



    - On Page SEO for New Domains
    - Improve Your Site`s Speed
    - Safari Books Online Review
    - Creating an Estore From the Ground Up
    - Most Common SEO Mistakes Developers Make
    - Making the Most of Your Titles and Meta Desc...
    - Five Ways Using Flash Can Damage Your Site
    - A Web Designer`s Guide to Colors
    - Use Webstarts to Create a Free Site
    - More Than Just Looks. How Your Web Design C...
    - How to Design Content Pages
    - Mint Review
    - Make Your WordPress Website Look Professional
    - How to Create a Mobile Web Site
    - Meta Tags: Still Useful?

    Developer Shed Affiliates


    © 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap