Tutorial Downloads .com

Home

BEGINNING PHP4 : GENERATING GRAPHICS PART 6 - ADVANCED GRAPHICS MANIPULATION

BEGINNING PHP4 : GENERATING GRAPHICS PART 6 - ADVANCED GRAPHICS MANIPULATION DESCRIPTION Now that we understand the basics of image functions and how we can apply them, let's take a look at some of the more advanced functions, the concepts behind them and their application.

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:

//map.php
Header("Content-type: image/jpeg");

$image = ImageCreateFromJPEG("island.jpg");
$icon = ImageCreateFromJPEG("pin.jpg");
$width = ImageSX($icon);
$height = ImageSY($icon);

ImageCopyResized($image,$icon,174,200,0,0,$width,$height,$width,$height);
ImageJPEG($image);
ImageDestroy($image);

?>

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():

//map.php
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);

ImageCopyResized($image,$icon,174,200,0,0,$width,$height,$width,$height);
ImageJPEG($image);
ImageDestroy($image);

?>

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:

//color_table.php
$image = ImageCreateFromJPEG("pin.jpg");
echo "\n";
for ($y=0;$y<4;$y++) {
echo "\n";
for ($x=0;$x<4;$x++) {
$temp = ImageColorAt($image,$x,$y);
$colorarray = ImageColorsForIndex($image,$temp);
echo "\n";
}
}
echo "
";
echo "".$colorarray["red"]."
\n";
echo "".$colorarray["green"]."
\n";
echo "".$colorarray["blue"]."
\n";
echo "
\n";
ImageDestroy($image);
?>

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:

//color_count.php
$image = ImageCreateFromJPEG("island.jpg");
echo ImageColorsTotal($image);
ImageDestroy($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:

//map2.php
Header("Content-type: image/png");
$image = ImageCreateFromPNG("island.png");
$icon = ImageCreateFromPNG("pin.png");
$trans = ImageColorAt($icon,0,0);
ImageColorTransparent($icon,$trans);
$width = ImageSX($icon);
$height = ImageSY($icon);
ImageCopyResized($image,$icon,174,200,0,0,$width,$height,$width,$height);
ImagePNG($image);
ImageDestroy($image);
?>

Summary

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.


Resource:
Posted By : PHPbrain
On date : 06.03.08

Most used PHP Tutorials

PHP Tutorials ( Ebooks , PDF's )
A Programmer’s Introduction to PHP 4.0 John.Wiley.and.Sons.PHP5.and.MySQL.Bible.eBook.pdf New Riders - PHP Functions Essential Reference.chm The Underground PHP and Oracle Manual
BEGINNING PHP4 : GENERATING GRAPHICS PART 1 - LAYING A FOUNDATION
BEGINNING PHP4 : GENERATING GRAPHICS PART 1 - LAYING A FOUNDATION DESCRIPTION PHP contains a range of functions that allow you to open, manipulate and output graphics to the web browser. During this chapter we will explore how these functions work and how we can apply them to display our data.
PHP Handout ( php pdf study material )
ATDB - 2004 PHP Handout - Volume 3 - PHP tutorial. Page - 1. Vol. 3 : PHP tutorial. PHP Handout. ATDB 2004. Page 2. ATDB - 2004 PHP Handout - Volume 3 - PHP …
PHP/MySQL Tutorial
Open source has brought a lot more than Linux to the computing world. It has also given us PHP and MySQL. According to Graeme, PHP and MySQL are the world’s best combination for creating data-driven sites. In the first installment of this three-lesson tutorial, our Kiwi guide covers everything you need to know to begin developing database hubs. He gives instructions for installation on both Unix and Windows, and then goes on to show some simple scripts that will insert information into a database and display that data on a Web page.
Beginning PHP and MySQL: From Novice to Professional, Third Edition
A comprehensive introduction to … the scripting language PHP and the MySQL database server. This book will not only expose … core aspects of both technologies, but will provide valuable insight into how they are used in unison to create dynamic data-driven Web applications.
Learning PHP, MySQL, and JavaScript: A Step-By-Step Guide to Creating Dynamic Websites
If you know HTML, this guide will have you building interactive websites quickly. You'll learn how to create responsive, data-driven websites with PHP, MySQL, and JavaScript, regardless of whether you already know how to program. Discover how the powerful combination of PHP and MySQL provides an easy way to build modern websites complete with dynamic data and user interaction. You'll also learn how to add JavaScript to create rich Internet applications and websites.
Magento Beginner's Guide
Get your Magento store up and running using Magento Beginner's Guide by William Rice.
Database Handling with PHP/MySQL Tutorial ( php pdf study material )
This php pdf study material gives Database Handling with PHP/MySQL Tutorial.Unlike other scripting languages for Web page development (i.e. ASP), PHP is open-source, crossplatform, and offers excellent connectivity to most of today’s common databases including Oracle, Sybase, Microsoft SQL Server, MySQL, Postgresql, ODBC (and others). PHP also offers integration with various external libraries which enable the developer to do anything from generating PDF docum ents, accessing secure payment services and producing graphic output, to parsing XML.
PHP and MySQL Web Development - tutorial Book
The PHP server-side scripting language and the MySQL database management system (DBMS) make a potent pair. Both are open-source products--free of charge for most purposes--remarkably strong, and capable of handling all but the most enormous transaction loads. Both are supported by large, skilled, and enthusiastic communities of architects, programmers, and designers. PHP and MySQL Web Development introduces readers (who are assumed to have little or no experience with the title subjects) to PHP and MySQL for the purpose of creating dynamic Internet sites. It teaches the same skills as introductory Active Server Pages (ASP) and ColdFusion books--technologies that address the same niche.
PHP - Advanced Tutorial
PHP - Advanced Tutorial
PHP 6 and MySQL 5 for Dynamic Web Sites: Visual QuickPro Guide
It hasn't taken Web developers long to discover that when it comes to creating dynamic, database-driven Web sites, MySQL and PHP provide a winning open source combination. Add this book to the mix, and there's no limit to the powerful, interactive Web sites that developers can create. With step-by-step instructions, complete scripts, and expert tips to guide readers, veteran author and database designer Larry Ullman gets right down to business: After grounding readers with separate discussions of first the scripting language (PHP) and then the database program (MySQL), he goes on to cover security, sessions and cookies, and using additional Web tools, with several sections devoted to creating sample applications.
AJAX Programming with PHP
This php pdf study material gives the details of AJAX Programming with PHP
PHP amp Zend Framework Tutorial
This php pdf study material gives the details of PHP amp Zend Framework Tutorial.PHP & Zend Framework Tutorial. I did a lot of googling, installing, re-installing, . but finally got my first php project to …
PHP-Nuke Tutorial
This php pdf study material gives the details of PHP-Nuke Tutorial..Encyclopedia - Definition of terms. Ephemerids - A “quote of the day” block. PHP-Nuke Tutorial. How to operate your PHP-Nuke website. 22603 West Main Street …
OReilly Learning PHP and MySQL 2nd Edition Aug 2007
OReilly Learning PHP and MySQL 2nd Edition Aug 2007

Latest added PHP Tutorials

Beginning PHP and MySQL: From Novice to Professional, Third Edition
A comprehensive introduction to … the scripting language PHP and the MySQL database server. This book will not only expose … core aspects of both technologies, but will provide valuable insight into how they are used in unison to create dynamic data-driven Web applications.
PHP 6 and MySQL 5 for Dynamic Web Sites: Visual QuickPro Guide
It hasn't taken Web developers long to discover that when it comes to creating dynamic, database-driven Web sites, MySQL and PHP provide a winning open source combination. Add this book to the mix, and there's no limit to the powerful, interactive Web sites that developers can create. With step-by-step instructions, complete scripts, and expert tips to guide readers, veteran author and database designer Larry Ullman gets right down to business: After grounding readers with separate discussions of first the scripting language (PHP) and then the database program (MySQL), he goes on to cover security, sessions and cookies, and using additional Web tools, with several sections devoted to creating sample applications.
The Essential Guide to Dreamweaver CS4 with CSS, Ajax, and PHP
Dreamweaver CS4 is a massive step forward in terms of integration with the rest of the CS4 suite (Flash, Fireworks, Photoshop, etc.), and also includes a whole host of exciting new features of its own. The Essential Guide to Dreamweaver CS4 with CSS, Ajax, and PHP concentrates on getting the best out of Dreamweaver CS4, rather than going into every menu item and toolbar icon. The emphasis is on developing websites compliant with the latest web standards, using CSS, JavaScript libraries (with particular emphasis on Spry, Adobe's implementation of Ajax), and PHP.
PHP and MySQL Web Development - tutorial Book
The PHP server-side scripting language and the MySQL database management system (DBMS) make a potent pair. Both are open-source products--free of charge for most purposes--remarkably strong, and capable of handling all but the most enormous transaction loads. Both are supported by large, skilled, and enthusiastic communities of architects, programmers, and designers. PHP and MySQL Web Development introduces readers (who are assumed to have little or no experience with the title subjects) to PHP and MySQL for the purpose of creating dynamic Internet sites. It teaches the same skills as introductory Active Server Pages (ASP) and ColdFusion books--technologies that address the same niche.
Learning PHP, MySQL, and JavaScript: A Step-By-Step Guide to Creating Dynamic Websites
If you know HTML, this guide will have you building interactive websites quickly. You'll learn how to create responsive, data-driven websites with PHP, MySQL, and JavaScript, regardless of whether you already know how to program. Discover how the powerful combination of PHP and MySQL provides an easy way to build modern websites complete with dynamic data and user interaction. You'll also learn how to add JavaScript to create rich Internet applications and websites.
Learn to Implement a Shopping Cart on your website using Zend Framework
This example-driven tutorial will takes you through the process of building Model-View-Controller-based web applications. Users will learn to create and develop a storefront application on their websites.
User Interaction and Email Automation
In this tutorial we will see how Symfony can generate nice looking forms for us, before creating our own formatting class. We then progress to create a fully customized form. We will also learn about how Symfony can be expanded to use the other third-party libraries, and how can we convert a module into a fully working plugin that can be packaged up and reused in other projects.
Agile works best in PHP.
In this tutorial, we will cover the following: • Introductions to agile philosophy, including agile values and agile principles • Common problems and fears that developers face while developing a product • What is meant by agility and how it can help • Extreme programming principles • Advantages of agile process models • Team agility • Agile process models • Agile principles for the PHP project team
Magento Beginner's Guide
Get your Magento store up and running using Magento Beginner's Guide by William Rice.
Macronimous - Writing clean, secure and easy to maintain PHP code
Any code when written in a clean, easy to understand and formatted way is readily accepted and acclaimed by one and all.