Skip Navigation LinksHome > Categories > Code from a Category

Creating images with PHP



User Name: serfcompany
Name: Serf
Contact Me: www.datawebcoder.com
Home Page: www.datawebcoder.com
php,mysql,javascript,html,css. Preferable working with Zend Framework. Good know javascript. I worked with various, javascript frameworks such as(jquery, YUI3, extjs, sencha touch). [More]
Viewed Times: 2045
Add Date: 03/23/2012
This article is intended for programmers with an average level of knowledge of PHP.This article describes how to use the GD library for image processing. GD is an external library, available as a PHP module.

PHP is not only ideally suited to display HTML pages, but also includes powerful tools for creating images "on the fly." Here are some examples:


* Create a button with the words, the text of which is stored in the database
* Graphical display of statistics
* Create a variety of charts and graphs


The purpose of this article


The article highlights the following issues:


* What are the headers (headers)
* Using the GD library to dynamically create images with PHP
* Using HTTP headers to indicate the browser that the output of PHP-script is the image


Creating a header


By default, PHP displays a header: Content-type: text / html, which means that the result of the script is an HTML code.



As you can see, PHP outputs Content-type: text / html, and a blank line before the script output. All the empty string is the title of HTTP.
The header contains information for the browser and not displayed on the screen.


The default header Content-type: text / html shows that the output HTML code that the browser should handle it.
If you change it say on the Content-type: text / plain, then the browser will simply accept the document as text and display it "as is" for headers in the output function is used in PHP header ().



Of course, not enough to send the header, you must also make sure to bring data into the proper format.
We should not think that just by sending a header Content-type: application / zip, and cast him out, "Hello", you can open the output of this script with WinZip'a.


Note: Web-server before sending the data to the client can add other titles in addition to Content-type, they are beyond the scope of this article.


What we need ?

Creating images in PHP GD library requires written by Thomas Boutell. (http://www.boutell.com/gd) Support the library is included when you compile PHP with the - with-gd.
To work with TrueType fonts may also need to library FreeType (http://www.freetype.org). Installation of both libraries is described in detail in the relevant documentation.


Create a images


Generation of images consists of three main steps:

* Create images
* Rendering images
* Display received images in the browser


To create an images using a function ImageCreate ().
The arguments the function takes the image width and height in pixels, and returns an identifier that is later used when calling the function to work with the image.


Before you draw anything, you must register the color that you want to use. To do this, does the ImageColorAllocate ().
This function is passed the ID images and three numbers that specify the color (RGB - red, green, blue).
The function returns a color identifier that is used in subsequent operations, rendering the image.


Example:



There are many functions that draw image.
Their full review is beyond the scope of this article. To familiarize with these functions, refer to the PHP


And finally, the image output by calling functions ImagePNG () or ImageGIF ().
The latter is not supported in the current version of GD due to licensing issues (the developers promise to renew support for GD GIF format after the July 7, 2004, when the patent expires on the compression algorithm Unisys LZW, used in the GIF.
After writing this article, the library was includes support for JPEG and WBMP.-ca. interpreter).
ImagePNG () converts the internal representation of images in the PNG file and sends it to the client. Similarly, works ImageGIF (), but using the format of the GIF. Before using the functions ImagePNG () or ImageGIF () to send the appropriate Content-type header.


Format Title
PNG "Content-type: image / png"
GIF "Content-type: image / gif"


Note: Titles are for the whole document.
That is, if you send a header indicating that you display them, you can not display text. And after you've taken out the first data byte, the header can not be changed!
This means that first you need to call the header () and only then start the output, otherwise you will get an error message.
If you are not sending the header Content-type, PHP automatically sends the Content-type: text / html as soon as you start to output.


How it looks in practice


Practical use of the GD library functions we consider the example of the script, building a graph of biorhythms.
Along the way, we give excerpts from the script code, which is completely contained in the article.


The theory of biorhythms, says that the emotional, physical and intellectual activity of each individual cycle changes at specific intervals.
At birth, all three curves out of the zero point and change throughout life.
If the curve is above zero - it is the active phase, below - passive.
The moment of crossing zero means the critical day you are at risk of emotional, physical or intellectual "catastrophe."
And in that day when all three curves pass through zero, it is better to refrain from working on important PHP projects.


Each curve own cycle:


* Physical: 23 days
* Emotional: 28 days
* Smart: 33 days


The curves represent a sine wave, so to calculate the values ??of jet lag, we can use the built-in function sin ().


Setting the date of birth


First we have to get a date of birth and calculate how many days a person has lived up to the current date.
The result will be used to compute the current phase of the biorhythm.


Procedure:


* Check whether the entered date of birth.
* If not, display a form for entering the date
* After validation I calculate how many days a person has lived up to the current date using the Julian calendar.



TIP: To calculate, we use the Julian calendar. Date of birth and current date are translated into the number of days according to the Julian calendar.
The difference between these two numbers gives the desired result.


Note: In this example, gregorianToJD () is implemented in PHP (see full code of the script below).
Actually, this feature is implemented in the calendar module, PHP, but at the time of this writing this feature to work correctly in the latest version of PHP. It was therefore used "homemade" function.
If your PHP-enabled features of the calendar, you need to delete the definition of the function of the code in the example.


Preparation of images


Procedure: Preparation for painting is made up of several functions call GD. The following code fragment:


* Creates an image of desired size.
* Registers used colors.
* Clears the images, filling it with color background



Tip: Before you start drawing images to fill the background color. This ensures that the background image will be the color that you want. It is also useful to create a transparent background, as will be shown later.


Note: For simplicity, the examples in this article do not include error checking. "This" script must include error checking.


Draw a frame and display the text


Function ImageString () draws a line of text in the image at the specified location. We need to take five lines.
The first two will be at the top of the figure and show the date of birth and current date, the other three under the graph will show how the color of which shows a biorhythm.
The use of color identifiers recorded in the variables that can refer to the color, not specifying the RGB value each time.


Procedure:


* Draw a frame within which the schedule will be posted, and the axis
* Print the text notes



Figure 1. The graph of biorhythms



Draw curves


Graphs biorhythms are sinusoids, differing only in the period, so we define the function drawRythm (), which shows a sinusoid with a given period.
This function will compute the values ??of jet lag for each day in a given period, and connect the points obtained lines.


Procedure:


* The drawRhythm called three times with different parameters
* The drawRhythm contains a loop that calculates the value of biorhythm for each day, and draws the line.



Tip: For a smooth curve should be used in the calculation intervals less than one day, but for the purposes of this article, the resulting image quality is sufficient.


The output images to the client


So, we drew our schedule. It now remains to send this image to the browser.


Procedure:


* Send the title, showing that we display the image in GIF or PNG.
* Determine the interlaced format output.
* Make the background color transparent.
* Using the function or imageGIF imagePNG derive an image.



Tip: When calling or imageGIF imagePNG, make changes to the image can not be because it has already been sent to the client.


Using ImageInterlace () allows you to set the mode of interlaced or progressive output images (if your image format allows it).
This mode is interesting because it allows the browser to start displaying pictures before it was fully downloaded.
First, displays an image of low quality, which improves as the data is loaded.
It is indispensable for the transmission of large images over low-speed channels.


Function ImageColorTransparent () sets the color of transparent areas of the image (again, if your format allows it).
In our example, we use a color that is stored in the variable $ colorBackgr, making parts of the image drawn in this color, transparent.
How to use the resulting image


So we wrote a program that creates the image.
How do I use it?
In fact, everything is very simple: You can use the script in the HTML code as a regular image file.
Because the script in our example is interactive, then to use it, we need to introduce http://my.server.net/script.php in your browser.
For a script that does not require user input, such as receiving information from the database, simply paste the HTML code for the page tag this content: img src="http://my.server.net/script.php"


The full code of the script



Conclusion


This article describes the basics of creating images in PHP using the graphical library GD.
In a rather complex example demonstrates how to create images based on user input.
Based on this example, you can create images to meet your specific objectives.

Post a Comment

Name: (Optional)
Email: (Optional, you can get an email if somebody replys your comments)*
Email me if somebody respons my comment below:
Details**:
Enter Text
as Below:
(case insensitive, if hard to read, click the "get a new one" button)
 
    
* Your email address will not be shared with any third parties for any reason.
** Maximum 1000 charactors.