<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>PHP Starter &#187; GD Library</title>
	<atom:link href="http://phpstarter.net/tag/gd-library/feed/" rel="self" type="application/rss+xml" />
	<link>http://phpstarter.net</link>
	<description>PHP Tips &#38; Tools From Starters to Experts</description>
	<lastBuildDate>Fri, 25 Jun 2010 14:14:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Dynamically Converting Text to an Image</title>
		<link>http://phpstarter.net/2009/02/dynamically-converting-text-to-an-image/</link>
		<comments>http://phpstarter.net/2009/02/dynamically-converting-text-to-an-image/#comments</comments>
		<pubDate>Thu, 05 Feb 2009 06:00:28 +0000</pubDate>
		<dc:creator>Kurtis</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[GD Library]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=337</guid>
		<description><![CDATA[As CSS expands, so does web design as a whole, but where it still lacks (and most likely will always lack) is in the area of fonts.  Depending on the user's home computer and the actions he/she has taken on it, there are different fonts inherently available.  In this article, however, we will talk about bypassing the user's system and use the fonts you would like, via PHP and the GD library.
No related posts.]]></description>
			<content:encoded><![CDATA[<p>As CSS expands, so does web design as a whole, but where it still lacks (and most likely will always lack) is in the area of fonts.  Depending on the user&#8217;s home computer and the actions he/she has taken on it, there are different fonts inherently available.  In this article, however, we will talk about bypassing the user&#8217;s system and use the fonts you would like, via PHP and the GD library.<span id="more-337"></span></p>
<p>SEO experts would say using images to replace text is a bad idea because crawlers cannot read the text on images to analyze the content on your website, but this process will effectively use JavaScript to overcome that.  First, we&#8217;ll talk about the basic idea of creating an image with the text using a basic GD function, <a href="http://www.php.net/imageloadfont" target="_blank">imageloadfont()</a>.</p>
<pre class="brush: php">

&lt;?php

$font = imageloadfont(&quot;path/to/font.gdf&quot;);

?&gt;
</pre>
<p>You can see the file is in a strange format, but you can safely use <a href="http://www.wedwick.com/wftopf.exe" target="_blank">this program</a> to convert Windows font files to the necessary format.  Using this program within the spectrum of an image created with PHP, text can be written on the image with a certain font:</p>
<pre class="brush: php">

&lt;?php

$string = &quot;Your string goes here&quot;;

//You should define the next two based on the font you are using

$charwidth = ...;

$charheight = ...;

$imagewidth = ($charwidth*strlen($string));

$text = imagecreatetruecolor = ($imagewidth,$charheight);

$font = imageloadfont(&quot;path/to/font.gdf&quot;);

$white = imagecolorallocate($text,255,255,255);

$black = imagecolorallocate($text,0,0,0);

imagefill($text,0,0,$white);

imagestring($text,$font,0,0,$string,$black);

header(&quot;Content-type: image/png&quot;);

imagepng($text);

imagedestroy($text);

?&gt;
</pre>
<p>You can see the image is tailored to fit the text so there is no extra whitespace.  The only downside is that the &#8216;charwidth&#8217; and &#8216;charheight&#8217; variables have to be altered for different fonts.</p>
<p>With just this basic script you can turn text into an image, but how about returning to the overarching idea of dynamically turning text on a website into an image to utilize a desired font.  We&#8217;ll use some simple JavaScript for that.</p>
<p>Note: I&#8217;m using the most basic template of an HTML file to show the idea of the script.</p>
<pre class="brush: html">

&lt;html&gt;

&lt;head&gt;
&lt;title&gt;Text to Image Conversion&lt;/title&gt;

&lt;script type=&#039;text/javascript&#039;&gt;

function text2img() {

htwo = document.getElementsByTagName(&quot;h2&quot;);

for (i=0,tot=htwo.length;i&lt;tot;i++) {

text = htwo.innerHTML;

htwo.innerHTML = &quot;&lt;img src=&#039;text2img.php?s=&quot;+text+&quot;&#039; alt=&#039;&quot;+text+&quot;&#039; /&gt;&quot;;

}

&lt;/script&gt;
&lt;body onload=&quot;text2img();&quot;&gt;

&lt;h2&gt;This will become an image&lt;/h2&gt;

&lt;p&gt;This won&#039;t become an image.&lt;/p&gt;

&lt;h2&gt;This will also become an image.&lt;/h2&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Referencing the PHP file we created in the JavaScript of this file will turn each &#8216;h2&#8242; element into an image.  As I mentioned earlier, this will not mess with most search engines, though, because the text will remain for those where JavaScript is turned off.  Note, though, that that also means that users with JavaScript disabled will not see the fancy image either, just the plain text, so be sure to style it with CSS as well to insure the design of your website.</p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/02/dynamically-converting-text-to-an-image/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Editing Images &#8211; Resizing, Cropping, and more!</title>
		<link>http://phpstarter.net/2009/01/editing-images-resizing-cropping-and-more/</link>
		<comments>http://phpstarter.net/2009/01/editing-images-resizing-cropping-and-more/#comments</comments>
		<pubDate>Thu, 29 Jan 2009 06:00:09 +0000</pubDate>
		<dc:creator>Kurtis</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[GD Library]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=295</guid>
		<description><![CDATA[We&#8217;ve seen the graphics PHP can create for you, but how extensive is PHP&#8217;s ability to edit preexisiting images? In this article, I will explore some common functions that image editing software provides, but I&#8217;ll only use PHP.  We&#8217;ll focus mainly on cropping, resizing, flipping, and adding some effects to photos.Of course there are hundreds [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>We&#8217;ve seen the graphics PHP can create for you, but how extensive is PHP&#8217;s ability to edit preexisiting images?  In this article, I will explore some common functions that image editing software provides, but I&#8217;ll only use PHP.  We&#8217;ll focus mainly on cropping, resizing, flipping, and adding some effects to photos.<span id="more-295"></span>Of course there are hundreds of image editing software packages available, many for free, but there is something to be said for editing images with PHP.  In fact, it just may be that working with graphics may mean utilizing internet programs to do what we typically do with programs like Photoshop.</p>
<p>First of all, let&#8217;s talk about cropping and resizing images as the two use the same function, just in a slightly different way.  The function is <a href="http://www.php.net/imagecopyresampled" target="_blank">imagecopyresampled()</a>.</p>
<pre class="brush: php">

&lt;?php

imagecopyresampled($new,$orig,$newX,$newY,$oldX,$oldY,$newWidth,$newHeight,$oldWidth,$oldHeight);

?&gt;
</pre>
<p>It&#8217;s quite a doozy, but all of the parameters are self-explanatory.  The variables &#8216;newX&#8217; and &#8216;oldX&#8217; refer to the new starting x-coordinates and old coordinate, respectively, and so on for the y-coordinates as well.</p>
<p>To crop an image, the idea is that we select a rectangular section of the original image and copy it to a new image.  Realize that in this case the &#8216;oldWidth&#8217; and &#8216;oldHeight&#8217; variables refer to the selection cropped, not the entire original image.  The process looks like this:</p>
<pre class="brush: php">

&lt;?php

//Cropping an image
header(&quot;Content-type: image/jpeg&quot;);

$top = ...; //Define upper-most pixel of selection

$bottom = ...; //Define lower-most pixel of selection

$left = ...; //Define left-most pixel of selection

$right = ...; //Define right-most pixel of selection
$image = imagecreatefromjpeg(&quot;/path/to/image.jpg&quot;); //Function matches file type

$new = imagecreatetruecolor(($right-$left),($bottom-$top)); //Becomes width,height

imagecopyresampled($new,$image,0,0,$left,$top,($right-$left),($bottom-$top),($right-$left),($bottom-$top));

imagejpeg($new,null,100);

imagedestroy($new);

imagedestroy($image);

?&gt;
</pre>
<p>Next is the very similar resizing function.  The only difference with resizing is that you don&#8217;t need to pick a certain area of the image; the entire image will be copied, simply at a different width and height.</p>
<pre class="brush: php">

&lt;?php

//Resizing an image
header(&quot;Content-type: image/jpeg&quot;);

$newWidth = ...; //Define new image&#039;s width

$newHeight = ...; //Define new image&#039;s height
$image = imagecreatefromjpeg(&quot;/path/to/image.jpg&quot;); //Function matches file type

list($width,$height) = getimagesize(&quot;/path/to/image.jpg&quot;); //Get old width and height

$new = imagecreatetruecolor($newWidth,$newHeight);

imagecopyresampled($new,$image,0,0,0,0,$newWidth,$newHeight,$width,$height);

imagejpeg($new,null,100);

imagedestroy($new);

imagedestroy($image);

?&gt;
</pre>
<p>You can see that these two ideas are very closely related, so there isn&#8217;t much difference between the two functions.  Next, let&#8217;s talk about flipping images, both horizontally and vertically.</p>
<p>There are two new functions we&#8217;ll talk about here, one that gets the color of the image at a specified pixel, and the other sets the color of the image at a specified pixel.</p>
<pre class="brush: php">

&lt;?php

$color = imagecolorat($image,$x,$y); //Get color

imagesetpixel($image,$x,$y,$color); //Set color

?&gt;
</pre>
<p>The only other thing we need to talk about is the idea of rolling through each pixel, and we&#8217;ll do this using two simultaneous &#8216;for&#8217; statements, one that runs through the image pixel-by-pixel horizontally, and another one that runs through each vertically at the same time.  This will allow us to get and set the color of each pixel in the image.</p>
<p>To flip an image horizontally, the left-most pixel becomes the right-most and vice-versa.  The top-most and bottom-most pixels switch when we flip vertically.  The process looks like this:</p>
<pre class="brush: php">

&lt;?php

$type = ...; //Define flip type (horizontal or vertical)

$image = imagecreatefromjpeg(&quot;/path/to/image.jpg&quot;); //Function matches file type
list($width,$height) = getimagesize($imagepath); //Get width and height
$new = imagecreatetruecolor($width,$height);  //Becomes new width and height
for ($x=0; $x&lt;$width; $x++) {
for ($y=0; $y&lt;$height; $y++) {
$color = imagecolorat($image,$x,$y); //Get pixel color
if ($type == &quot;horizontal&quot;) {
imagesetpixel($new,(($width-1)-$x),$y,$color);
}
else { //Type is vertical
imagesetpixel($new,$x,(($height-1)-$y),$color);
}
}
}

imagejpeg($new,null,100);

imagedestroy($new);

imagedestroy($image);

?&gt;
</pre>
<p>Last, but not least, I&#8217;ll show you how to apply several different types of effects to an image, and this doesn&#8217;t require any special calculations, just one function, <a href="http://php.net/imagefilter" target="_blank">imagefilter()</a>.  You can read about all of the different filters available, but the main ones are blurring, converting to gray scale, and changing contrast/brightness.</p>
<p>With these GD functions in tow, there is very little you can&#8217;t do with PHP.  Alright, so there&#8217;s still quite a bit that PHP can&#8217;t do with images practically, but it&#8217;s only a matter of time before programmers are able to apply even the most complex Photoshop functions to PHP.</p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/01/editing-images-resizing-cropping-and-more/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Very Basic Pie Chart</title>
		<link>http://phpstarter.net/2008/12/very-basic-pie-chart/</link>
		<comments>http://phpstarter.net/2008/12/very-basic-pie-chart/#comments</comments>
		<pubDate>Tue, 30 Dec 2008 06:00:06 +0000</pubDate>
		<dc:creator>Kurtis</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[GD Library]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=201</guid>
		<description><![CDATA[Pie chart, circle graph, call it what you want, but these charts are loved by descriptive statisticians across the world for their instant appeal to the viewer&#8217;s eyes and inferential mind.  Though descriptive statistics can be deceiving, pie charts, created in this article with the GD library, easily describe the data in a very literal [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>Pie chart, circle graph, call it what you want, but these charts are loved by descriptive statisticians across the world for their instant appeal to the viewer&#8217;s eyes and inferential mind.  Though descriptive statistics can be deceiving, pie charts, created in this article with the GD library, easily describe the data in a very literal way.  In this post, we&#8217;ll go over the basic GD functions available for putting together a simple pie chart.</p>
<p><span id="more-201"></span>So far in the GD library series, I&#8217;ve detailed several key functions that one should certainly know before diving in to an extensive project.  To review some of these functions as involved with an application, check out the <a href="http://phpstarter.net/tag/gd-library/">series thus far</a>.</p>
<p>Now that you know about declaring colors, fonts, and setting up the basics of the image, let&#8217;s get right to revealing the newest (and only new) function in this article, <a href="http://www.php.net/imagefilledarc" target="_blank">imagefilledarc()</a>, declared like this:</p>
<pre class="brush: php">

&lt;?php

...

imagefilledarc($img,$cX,$cY,$width,$height,$startDeg,$endDeg,$col,$style);

...

?&gt;
</pre>
<p>Now, let&#8217;s break this down, as this is quite a hefty function:</p>
<ul>
<li>$img = The image you are working with, established with something like <a href="http://www.php.net/imagecreate" target="_blank">imagecreate()</a></li>
<li>$cX, $cY = The coordinates of the pixel that will be the center of the arc, and in this case, the entire pie chart</li>
<li>$width, $height = Quite obviously, the width and height of the arc, meaning the pixel span horizontally and then vertically</li>
<li>$startDeg, $endDeg = The starting and ending point on the circle for the arc, in degrees</li>
<li>$col = The color to fill the arc with, as established earlier with<a href="http://www.php.net/imagecolorallocate" target="_blank"> imagecolorallocate()</a></li>
<li>$style = One of several styles available, including <strong>IMG_ARC_PIE</strong>, <strong>IMG_ARC_CHORD</strong>, <strong>IMG_ARC_NOFILL</strong>, <strong>IMG_ARC_EDGED</strong>, and in this article we&#8217;ll be focusing on <strong>IMG_ARC_PIE</strong></li>
</ul>
<p>With this basic understanding of the function, let&#8217;s put together a basic pie chart with everything we know.  We&#8217;ll begin, as we typically do, by establishing the image and creating a blank, white canvas to work with.</p>
<pre class="brush: php">

&lt;?php

$pie = imagecreate(500,500);

$white = imagecolorallocate($pie,255,255,255);

imagefill($pie,0,0,$white);

...

?&gt;
</pre>
<p>Obviously, if you were putting together an accurate pie chart, you would have actual data and statistics to work with, but in this case, we&#8217;re just running through the basics, so we&#8217;ll use rather even, easy percentages.  Next, we&#8217;ll create an array holding the five percentages that will define the five &#8220;slices&#8221; of the pie, and we&#8217;ll also load a font to use later with labeling.  You remember <a href="http://www.php.net/imageloadfont">how to load a font</a>, right?</p>
<pre class="brush: php">

&lt;?php

...

$font = imageloadfont(&#039;arial.gdf&#039;);

$black = imagecolorallocate($pie,0,0,0);  //This is for the labeling also

$percentages = array(&quot;40&quot;,&quot;30&quot;,&quot;15&quot;,&quot;10&quot;,&quot;5&quot;);

...

?&gt;
</pre>
<p>Next, we&#8217;ll put together that awesome pie (I understand if you&#8217;re starting to get hungry), and I like to use a simple <a href="http://www.php.net/for" target="_blank">for()</a> loop.  Either you can manually set the loop values if you know how many values you will have at all times, or you can make it a bit more dynamic, letting PHP do the calculations.  Let&#8217;s do this slowly, simply setting up the loop and the calculations.</p>
<pre class="brush: php">

&lt;?php

...

$x = 0;

for ($z=0, $c=count($percentages); $z&lt;$c; $z++) {

$degrees = (($percentages[$z]/100)*360);

$color = imagecolorallocate($pie,mt_rand(20,255),mt_rand(20,255),mt_rand(20,255));

...

?&gt;
</pre>
<p>With just this, we are ready to create the &#8220;slices&#8221; of the pie, but I want to be sure a couple of things about the loop are made clear.  First of all, if you are going to use the <a href="http://www.php.net/count" target="_blank">count()</a> function to set the limit, establish it with the incrementing variable; otherwise, PHP will have to calculate it each time the loop is run through which demands more time and resources.  Also, make sure you understand the reason for the variable before the loop. With this, we establish &#8216;x&#8217; as the starting degree and set it to &#8217;0,&#8217; as that is where we want to start.  When calculating the degrees for each element, you can actually just multiply the percentage by 3.6, but I wanted to be sure it was obvious what I was doing there.  Lastly, we dynamically set a color, as we want each &#8220;slice&#8221; to be different.  In reality, we could end up with two slices of the same color, but the chances are slim.  Feel free to take the necessary precautions to prevent this, if you wish.  Now, let&#8217;s get to the most important part, making, not baking, a pie:</p>
<pre class="brush: php">

&lt;?php

...

$x = 0;

for ($z=0, $c=count($percentages); $z&lt;$c; $z++) {

$degrees = (($percentages[$z]/100)*360);

$color = imagecolorallocate($pie,mt_rand(20,255),mt_rand(20,255),mt_rand(20,255));

imagefilledarc($pie,100,100,125,125,$x,($x+$degrees),$color,IMG_ARC_PIE);

imagefilledrectangle($pie,250,(50+(25*($z+1))),275,(75+(25*($z+1))),$color);

imagestring($pie,$font,276,(55+(25*($z+1))),$vals[$z].&quot;%&quot;,$black);

$x+=$degrees;

}

header(&quot;Content-type: image/png&quot;);

imagepng($pie);

imagedestroy($pie);

?&gt;
</pre>
<p>Finally, we have our pie chart.  We simply use the calculations we already found, along with whatever center, width, and height you wish to use to draw the pie.  Then, we simply label the pie with the corresponding percentages.  With a more complex script, you could easily label the pie with the actual descriptors for each &#8220;slice.&#8221;  Finally, we add on the total degrees to reset the starting value for the next section.  Then, output the image and your pie is ready to eat, or rather, look at.</p>
<p>I want to stress with this script that I titled it quite appropriately; this is a <strong>basic </strong>pie chart.  There are definitely ways to make it look more appealing, certainly, but with this basic setup, you are on your way to becoming a professional statistician, except for all that fancy math behind it.</p>
<p>Check out a <a href="http://www.phpstarter.net/samples/201/piechart_maker.php">sample pie chart</a>; enter a list of percentages (that must add up to 100; there is nothing in place to check for this) and watch your pie come to life.</p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2008/12/very-basic-pie-chart/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Histograms &#8211; Remember the GD library?</title>
		<link>http://phpstarter.net/2008/12/histograms-remember-the-gd-library/</link>
		<comments>http://phpstarter.net/2008/12/histograms-remember-the-gd-library/#comments</comments>
		<pubDate>Tue, 23 Dec 2008 06:00:36 +0000</pubDate>
		<dc:creator>Kurtis</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[GD Library]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=181</guid>
		<description><![CDATA[Better recognized perhaps as &#8220;bar graphs&#8221; to most people, in the world of statistics, histograms provide a graphic representation of a set of data.  This graph can be used to make inferences about the data and draw conclusions about the sample and population.  In this article, we&#8217;ll dive into a few new functions available as [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>Better recognized perhaps as &#8220;bar graphs&#8221; to most people, in the world of statistics, histograms provide a graphic representation of a set of data.  This graph can be used to make inferences about the data and draw conclusions about the sample and population.  In this article, we&#8217;ll dive into a few new functions available as part of the GD library that are particularly useful for this application.</p>
<p><span id="more-181"></span>As always, we will take a step-by-step approach toward handling the complicated script, and I would like to preface by saying that my &#8220;finished&#8221; code is not the best, but the use of the main functions I will discuss here is what is most important.  Let&#8217;s start by setting up the image and creating the axes.  The math is not too important and can be computed in many ways.  Depending on the image size and spread you want, the numbers can certainly change.  Just remember that the upper-left corner of the image is (0,0) and the bottom-right corner is (max,max), so adjust your coordinates accordingly.  With the following code, we will analyze the set of data mathematically, determining the individual classes (which will each be represented with a bar), the frequency of each, the number of pixels on the image that will represent a frequency of &#8217;1&#8242; (Yscl), and the width of the image based on the number of classes there are.  Then, we will draw the x and y-axes.</p>
<pre class="brush: php">

&lt;?php
$x = explode(&quot;a&quot;,$_GET[&#039;x&#039;]);
$numClasses = $_GET[&#039;nC&#039;];
$min = (float)$x[0];
$max = (float)$x[0];
foreach ($x as $val) {
if ((float)$val&lt;$min) { $min = $val; }
if ((float)$val&gt;$max) { $max = $val; }
}
$c = ceil((($max-$min)/$numClasses));
for ($z=0; $z&lt;$numClasses; $z++) {
$class{$z} = array((($z*$c)+$min),((($z+1)*$c)+($min-1)),0);
foreach ($x as $val) {
if (($val &gt;= $class{$z}[0]) &amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp; ($val &lt;= $class{$z}[1])) {
$class{$z}[2]++;
}
}
}
$maxCount = 0;
for ($z = 0; $z&lt;$numClasses; $z++) {
if ($class{$z}[2] &gt; $maxCount) {
$maxCount = $class{$z}[2];
}
}
$Yscl = (500/$maxCount);
$width = (70+($numClasses*70));

$histogram = imagecreate($width,560);

//Defining our colors here...you remember how to do that, right?

$white = imagecolorallocate($histogram,255,255,255);
$black = imagecolorallocate($histogram,0,0,0);
$blue = imagecolorallocate($histogram,0,0,255);
imageline($histogram,50,10,50,510,$black);
imageline($histogram,50,510,$width,510,$black);

...

?&gt;
</pre>
<p>Next, we&#8217;ll handle a quick, rather minor part, labeling the histogram using the imagestring() function.  There are several functions available with the GD library, including <a href="http://www.php.net/imagefttext" target="_blank">imagefttext()</a>, <a href="http://www.php.net/imagepstext">imagepstext()</a>, and <a href="http://www.php.net/imagettftext">imagettftext()</a>, so pick the one that&#8217;s best for you.  An accomplice to this function, we will also use imageloadfont() to add a basic font of our own to use.</p>
<pre class="brush: php">

&lt;?php

$font = imageloadfont(&#039;font.gdf&#039;);

imagestring($image,$font,$x,$y,&quot;Text&quot;,$color);

?&gt;
</pre>
<p>There are several specifications for the font file that you load, so I would read up on the <a href="http://www.php.net/imageloadfont" target="_blank">specifications</a> depending on the version of GD you have and what you want to accomplish.  We aren&#8217;t going to add any text to the chart yet, but I&#8217;ll add that on in the following code.  Finally, let&#8217;s actually get on to the most important part, creating the bars, using the imagefilledrectangle() function:</p>
<pre class="brush: php">

&lt;?php

imagefilledrectangle($image,$x1,$y1,$x2,$y2,$color);

?&gt;
</pre>
<p>The two coordinates that are needed should be opposite corners (upper-left and bottom-right,upper-right and bottom-left, etc), though it is not important which two.  As you should know by now, $image refers to the image you create and $color to a predefined color that the rectangle will be filled with.  Computing the sizes of each rectangle and adding in the proper labels, here&#8217;s the additional code:</p>
<pre class="brush: php">

&lt;?php

imageloadfont(&#039;arial.gdf&#039;);

imagestring($histogram,$font,(($width/2)-25),527,&quot;Classes&quot;,$blue);
for ($z=0; $z&lt;$numClasses; $z++) {
imagefilledrectangle($histogram,(70+(69*$z)),509,((69*$z)+120),(509-($Yscl*$class{$z}[2])),$blue);
imagestring($histogram,$font,(67+(69*$z)),511,$class{$z}[0].&quot;-&quot;.$class{$z}[1],$black);
imagestring($histogram,$font,30,(509-($Yscl*$class{$z}[2])),$class{$z}[2],$blue);
imageline($histogram,47,(509-($Yscl*$class{$z}[2])),53,(509-($Yscl*$class{$z}[2])),$black);
}
</pre>
<p>As you can see, we used the imagestring() function to label the x-axis, label each class of the histogram, and label the necessary heights on the y-axis to make it easy-to-read.</p>
<p>All-in-all, the code I use reads as follows, and I think you will see that with exception perhaps to adjusting the coordinates to fit with the image, it is not too complicated.</p>
<pre class="brush: php">

&lt;?php
$x = ;//Array of x-values
$numClasses = ;//Desired number of classes
$min = (float)$x[0];
$max = (float)$x[0];
foreach ($x as $val) {
if ((float)$val&lt;$min) { $min = $val; }
if ((float)$val&gt;$max) { $max = $val; }
}
$c = ceil((($max-$min)/$numClasses)); //Width of each class
for ($z=0; $z&lt;$numClasses; $z++) {
$class{$z} = array((($z*$c)+$min),((($z+1)*$c)+($min-1)),0);
foreach ($x as $val) {
if (($val &gt;= $class{$z}[0]) &amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp; ($val &lt;= $class{$z}[1])) {
$class{$z}[2]++;
}
}
}
$maxCount = 0;
for ($z = 0; $z&lt;$numClasses; $z++) {
if ($class{$z}[2] &gt; $maxCount) {
$maxCount = $class{$z}[2];
}
}
$Yscl = (500/$maxCount);
$width = (70+($numClasses*70));
$histogram = imagecreate($width,560);
$white = imagecolorallocate($histogram,255,255,255);
$black = imagecolorallocate($histogram,0,0,0);
$blue = imagecolorallocate($histogram,0,0,255);
$font = imageloadfont(&#039;arial.gdf&#039;);
imageline($histogram,50,10,50,510,$black);
imageline($histogram,50,510,$width,510,$black);
imagestring($histogram,$font,(($width/2)-25),527,&quot;Classes&quot;,$blue);
for ($z=0; $z&lt;$numClasses; $z++) {
imagefilledrectangle($histogram,(70+(69*$z)),509,((69*$z)+120),(509-($Yscl*$class{$z}[2])),$blue);
imagestring($histogram,$font,(67+(69*$z)),511,$class{$z}[0].&quot;-&quot;.$class{$z}[1],$black);
imagestring($histogram,$font,30,(509-($Yscl*$class{$z}[2])),$class{$z}[2],$blue);
imageline($histogram,47,(509-($Yscl*$class{$z}[2])),53,(509-($Yscl*$class{$z}[2])),$black);
}
header(&quot;Content-type: image/png&quot;);
imagepng($histogram);
imagedestroy($histogram);
?&gt;
</pre>
<p>With this, a great-looking histogram is achieved, and the colors and text can easily be modified to combine for the look desired.  PHP and the GD library once again save the day, making it easier for statisticians to graphically represent data.</p>
<p>Check out my <a href="http://phpstarter.net/samples/181/histogram_maker.php" target="_blank">sample script</a>, where you can enter a set of data and a number of classes (can be random) and be presented a basic histogram.</p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2008/12/histograms-remember-the-gd-library/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scatter plots &#8211; An Application of the GD Library</title>
		<link>http://phpstarter.net/2008/12/scatter-plots-an-application-of-the-gd-library/</link>
		<comments>http://phpstarter.net/2008/12/scatter-plots-an-application-of-the-gd-library/#comments</comments>
		<pubDate>Tue, 16 Dec 2008 06:00:44 +0000</pubDate>
		<dc:creator>Kurtis</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[GD Library]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=154</guid>
		<description><![CDATA[Easily the most useful application of the GD library is the ability to dynamically output clean, sharp graphs and charts.  A scatter plot, the plotting of points based on an independent variable and the dependent variable (usually X and Y), is a great application that uses several common GD functions and is useful for data [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>Easily the most useful application of the GD library is the ability to dynamically output clean, sharp graphs and charts.  A scatter plot, the plotting of points based on an independent variable and the dependent variable (usually X and Y), is a great application that uses several common GD functions and is useful for data analysis as well.  In this post, I&#8217;ll highlight those functions while explaining the math behind using PHP to create a great scatter plot.</p>
<p><span id="more-154"></span></p>
<p>Because this series has been written to focus mainly on the capabilities of the GD library, I wish to stray from focusing too heavily on the mathematical aspects of creating a scatter plot, as interesting as they are in this case.  Perhaps I will comment on it in the future, but for now, let us focus on the main PHP functions available to work with graphing.</p>
<p>Whether you use a form to input your x and y-values or obtain them from the URL parameters, the data should be handled like two lists, one containing all of the x-values and the other with the corresponding y-values in the order in which they pair up with the x-values.  Believe it or not, there are only two new functions since the <a href="http://phpstarter.net/2008/12/working-with-images-introducing-the-gd-library/" target="_self">introductory GD library post</a> that need to be explained, and they will be detailed now.</p>
<p>The first is the function to draw a line, appropriately called in the following manner:</p>
<pre class="brush: php">

&lt;?php

imageline($image,$x1,$y1,$x2,$y2,$color);

?&gt;
</pre>
<p>This function is used to draw the two axes, starting with the point ($x1,$y1) extending to the point ($x2,$y2).  The color should be defined previously using &#8220;imagecolorallocate,&#8221; as well as the image itself using any of the available functions.  While straight integer values can be used as the coordinates, they can be obtained from calculations, either called by variables or through direct computation.  This capability can make for dynamic line placement and drawing.</p>
<p>Let&#8217;s apply this function to our main example, the scatter plot.  The main use of lines in a scatter plot is in the x and y-axes.  The two axes should be placed relative to the minimum x and y values obtained from the two lists.  To create the two axes, let&#8217;s do the following:</p>
<pre class="brush: php">

&lt;?php

...

$Xmin = 0;
$Xmax = 0;
$Ymin = 0;
$Ymax = 0;
foreach ($x as $val) {
if ($val&lt;$Xmin) { $Xmin = $val; }
if ($val&gt;$Xmax) { $Xmax = $val; }
}
foreach ($y as $val) {
if ($val&lt;$Ymin) { $Ymin = $val; }
if ($val&gt;$Ymax) { $Ymax = $val; }
}
$Xmin -= 1;
$Xmax += 1;
$Ymin -= 1;
$Ymax += 1;
$Yscl = (500/($Ymax-$Ymin));
$Xscl = (500/($Xmax-$Xmin));
imageline($graph,0,round(499-($Yscl*($Ymin*-1))),500,round(499-($Yscl*($Ymin*-1))),$axes);
imageline($graph,round($Xscl*($Xmin*-1)),0,round($Xscl*($Xmin*-1)),500,$axes);

...

?&gt;
</pre>
<p>One thing to realize with creating graphs with the GD library is that images do not work like Cartesian coordinate planes.  With respect to images, the top-left corner is (0,0) and the bottom-right corner is (max,max), so complex calculations are necessary to compute the proper coordinates.</p>
<p>Now for the meat of the graph: the points.  The second new function is used to draw the points themselves, used in the following manner:</p>
<pre class="brush: php">

&lt;?php

imagefilledellipse($graph,$cx,$cy,$width,$height,$color);

?&gt;
</pre>
<p>Surely you can see that the function is used to draw an ellipse, but if the width and height are equal, a circle would be created.  In the creation of a scatter plot, the center coordinates would be the representation of the x and y-values, whereas the width and height would be based either on the thickness desired or, to extend the functionality of the graph, on the frequency of that data.  I suggest making it as complicated as you need; points of the same size work just fine.</p>
<p>To add the points to the graph, we add the following code, utilizing the aforementioned function:</p>
<pre class="brush: php">

&lt;?php

...

for ($c=0,$z=count($x); $c&lt;$z; $c++) {
$xPt = round($Xscl*($x[$c]+($Xmin*-1)));
$yPt = round((500-($Yscl*($y[$c]+($Ymin*-1)))));
imagefilledellipse($graph,$xPt,$yPt,7,7,$point);
}

...

?&gt;
</pre>
<p>The for() loop is used here so we can run through the x and y arrays at the same time to get the corresponding coordinates, and then the imagefilledellipse() function draws the points on.  The width and height do not have to be 7; choose an appropriate size based on your need.</p>
<p>Lastly, we use the imageline() function again to draw on the line of best fit for the data, and this part is definitely optional, but for statisticians it is typically the most important.  The code is as follows, calculating the beginning and ending y values and then drawing the line:</p>
<pre class="brush: php">

&lt;?php

...

$Yone = round((500-($Yscl*((($Xmin*$a)+$b)+($Ymin*-1)))));
$Ytwo = round((500-($Yscl*((($Xmax*$a)+$b)+($Ymin*-1)))));
imageline($graph,0,$Yone,500,$Ytwo,$bestFit);

...

?&gt;
</pre>
<p>To create a great looking scatter plot, put the code all together to make something like this:</p>
<pre class="brush: php">

&lt;?php

header(&quot;Content-type: image/png&quot;);
$x = //Array of x values
$y = //Array of y values
$a = round(((($n*$sumXY) - ($sumX*$sumY))/(($n*$sumXSq)-pow($sumX,2))),3);

$b = round(((($sumY*$sumXSq)-($sumX*$sumXY))/(($n*$sumXSq)-pow($sumX,2))),3)
$graph = imagecreatetruecolor(500,500);
$gray = imagecolorallocate($graph,250,250,250);
$axes = imagecolorallocate($graph,200,200,200);
$bestFit = imagecolorallocate($graph,0,0,255);
$point = imagecolorallocate($graph,255,0,0);
imagefill($graph,0,0,$gray);
$Xmin = 0;
$Xmax = 0;
$Ymin = 0;
$Ymax = 0;
foreach ($x as $val) {
if ($val$Xmax) { $Xmax = $val; }
}
foreach ($y as $val) {
if ($val$Ymax) { $Ymax = $val; }
}
$Xmin -= 1;
$Xmax += 1;
$Ymin -= 1;
$Ymax += 1;
$Yscl = (500/($Ymax-$Ymin));
$Xscl = (500/($Xmax-$Xmin));
imageline($graph,0,round(499-($Yscl*($Ymin*-1))),500,round(499-($Yscl*($Ymin*-1))),$axes);
imageline($graph,round($Xscl*($Xmin*-1)),0,round($Xscl*($Xmin*-1)),500,$axes);
for ($c=0,$z=count($x); $c&lt;$z; $c++) {
$xPt = round($Xscl*($x[$c]+($Xmin*-1)));
$yPt = round((500-($Yscl*($y[$c]+($Ymin*-1)))));
imagefilledellipse($graph,$xPt,$yPt,7,7,$point);
}
$Yone = round((500-($Yscl*((($Xmin*$a)+$b)+($Ymin*-1)))));
$Ytwo = round((500-($Yscl*((($Xmax*$a)+$b)+($Ymin*-1)))));
imageline($graph,0,$Yone,500,$Ytwo,$bestFit);
header(&quot;Content-type: image/png&quot;);
imagepng($graph);
imagedestroy($graph);
?&gt;
</pre>
<p>As you can see, I added a few lines to allow spacing around the plot and changed a few colors, but the main idea is the same.  To check out a working example of the scatter plot, head over to the fully-functioning <a href="http://www.phpstarter.net/samples/154/linear_regression.php">linear regression model</a> and input two lists.  Focus on the picture at the bottom of the middle column; that&#8217;s the great looking scatter plot we just created!</p>
<p>The two functions discussed in this article have a lot of potential extending to other applications as well, including pie graphs and even graphing equations of lines.  The GD library, through mathematical analysis and application, can become quite a tool for mathematicians/statisticians for dynamically outputting sharp-looking representations.</p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2008/12/scatter-plots-an-application-of-the-gd-library/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Working with Images &#8211; Introducing the GD Library</title>
		<link>http://phpstarter.net/2008/12/working-with-images-introducing-the-gd-library/</link>
		<comments>http://phpstarter.net/2008/12/working-with-images-introducing-the-gd-library/#comments</comments>
		<pubDate>Tue, 09 Dec 2008 06:00:49 +0000</pubDate>
		<dc:creator>Kurtis</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[GD Library]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=76</guid>
		<description><![CDATA[There are hundreds of libraries available to add on to the PHP base, and GD is just one of those with thousands of possibilities.  Used to process images and even dynamically create and output graphics, the GD library is relatively easy to learn with distinct potential in the graphics world. In this article, I will [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>There are hundreds of libraries available to add on to the PHP base, and GD is just one of those with thousands of possibilities.  Used to process images and even dynamically create and output graphics, the GD library is relatively easy to learn with distinct potential in the graphics world.  In this article, I will establish the basics of image-handling functions to advance later.<br />
<span id="more-76"></span></p>
<p>Nearly any computer-literate user can click the mouse a few times and create a decent image with software like Photoshop or another graphics program, but there is much potential in the uses of the PHP GD library and its ability to construct images on the fly, like charts and graphs.  Additionally, it can be used in other manners, such as handling uploaded images and dynamically outputting thumbnails and edited images.</p>
<p>For the experimenter-at-heart, there may also be a future in image editing via the web, using PHP that is.  Some websites already handle activities like this, such as <a title="SnipShot - Online image editing" href="http://www.snipshot.com" target="_blank">SnipShot</a>, but they do not necessarily utilize fully the possibilities PHP provides.  It certainly does leave much to the imagination as to just what a programming language could do with images.</p>
<p>So how exactly is the GD libary used?  First, you should make sure you have it instead of spending forever stressing over error messages about undefined functions.  If you have PHP 4.3 or later, the GD libary was bundled with your version, so there&#8217;s no need to worry, though more libraries may be required for more image types and fonts.  Still not sure if you have the GD library?  Check your phpinfo by running the following function in an empty PHP file and opening it in your browser:</p>
<pre class="brush: php">
&lt;?php
phpinfo();
?&gt;
</pre>
<p>Searching for the &#8220;gd&#8221; section will help you determine if it is enabled or not, and once you have the library ready for use, it&#8217;s time to create a simple image.  However, I suggest you first take some time to familiarize yourself with the following terms/ideas:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Web_colors" target="_blank">RGB vs. hexadecimal color values</a></li>
<li><a href="http://www.google.com/search?hl=en&amp;safe=off&amp;client=firefox-a&amp;rls=org.mozilla%3Aen-US%3Aofficial&amp;hs=mr&amp;q=convert+rgb+to+hex&amp;btnG=Search" target="_blank">How to manipulate RGB and hexadecimal color values</a> (Any of the first few results work well)</li>
<li><a href="http://info.eps.surrey.ac.uk/FAQ/standards.html" target="_blank">Image types and their color/quality implications (e.g. JPEG, PNG, GIF, etc)</a></li>
</ul>
<p>The main thing to realize with outputting an image is that the content type must be declared before the image can truley be output to the page, whether directly in the page accessed or through inclusion of a separate PHP &#8220;image&#8221; file.  Below is an extremely basic image, as created with PHP, that we will analyze line-by-line to explain the main functions necessary to begin an image.</p>
<pre class="brush: php">
&lt;?php
header(&quot;Content-type: image/png&quot;);
$image = imagecreatetruecolor(300,300);
$black = imagecolorallocate($image,0,0,0);
imagepng($image);
imagedestroy($image);
?&gt;
</pre>
<p>Placing the code above in a PHP file should reveal a 300px-by-300px black square, and here&#8217;s how that is achieved:</p>
<ul>
<li>Line 2:  Declare the content type of the file.  The browser will read this as a PNG image.  Naturally, PNG can be replaced with any supported image type (e.g. GIF, JPEG, etc)</li>
<li>Line 3:  Create the image, and assign it to the variable &#8216;image.&#8217;  The values read as width, then height, in pixels.</li>
<li>Line 4:  Allocate a color to a variable, and in this case, assign that color as the background of the image.  Any and all colors used in the image must be established this way, calling the image variable first, then in RGB format, declaring the R, G, and B values.</li>
<li>Line 5:  Output the image to the file.  Depending on the image type, the function will change (e.g. images of type &#8216;gif&#8217; would use imagegif(), etc)</li>
<li>Line 6:  Destroy the memory associated with the image.  In many cases, this is necessary to keep future scripts working correctly, and to free memory and prevent overloading the server with large images.  Though sometimes the image will be destroyed automatically, you are better off doing it manually and being sure the space is free.</li>
</ul>
<p>With just these few lines, a (very basic) image is created.  Looking at the list of functions associated with the GD library, you can see that there is a myriad of things that can be accomplished with the library, and in the future I will detail some specific uses, but perhaps the best way to discover a new method is to experiment yourself, reading the documentation and trying out your own ideas.</p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2008/12/working-with-images-introducing-the-gd-library/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

