Archive for the '' Category

February 12th 2008

Adding text to images in real time with PHP

Using PHP and the GD library the task of manipulating images, editing them and even adding text before presenting it to the user becomes a simple feat. Since I had to make use of this tool recently while making "on-the-fly" cupons for a client, i decided to write this article showing how easy this can be done.

First Steps

Attention: verify that the GD library is installed using a phpinfo() command.

There are a few ways of outputting the image after finishing the process, for example:

  • Save the file to disc
  • Output image on screen (as an image, inside the HTML)
  • Output to screen (just the image code)

In this example we are going to output the image to a <img> tag inside the HTML code, but for this we must understand a little about how this structure fits together. Generally an image tag points to a ".jpg" or ".gif" file, but here we need it to point to a ".php" file. This file will be responsible for seeking the image, editing it (insert text) and outputting the raw image code that will be read by the <img> tag.

So as a result we will have three files: the main.php file, that will output our HTML code, the image.php file that will edit and output the image, and a img.jpg that will be our base image that we will add text to.

main.php

This is a simple and straight-through file with an image tag. The only twist here is that in the image src attribute we will include (via GET) the name that should be written on the image.

HTML:
  1. Get your certificate below&lt;br&gt;
  2.  
  3. <img src="imagem.php?nome=Rafael%20Dohms" />

imagem.php

This is where the magic begins, this file should retreive the original image, the input text, and join the two, outputting the image with the text in it. So let's go at it step by step.

The first step is to load the image into a PHP resource, basically loading it into the memory. PHP has a few functions for this, depending on the image's format: ImageCreateFromJPEG, ImageCreateFromGIF and so on ...

PHP:
  1. $rImg = ImageCreateFromJPEG( "ex-img.jpg" );

Now comes the time to write the text to the image, but first we need to get some parameters ready. There are basically two ways to write text on an image, one char at a time or a whole string at once (imagechar ou imagestring). In our example we will use the string method, but both receive the same parameters varying only on the text to be written. Before invoking the mothod we should setup the color to be used.

To do this we use the imagecolorallocate that receives as values the image resource and the color in RGB format (3 numbers) . In this case we use a black color:

PHP:
  1. $color = imagecolorallocate($rImg, 0, 0, 0);

Now we can begin writing. The function imagestring receives these parameters, in this order:

  • image: the image resource
  • font: an interger, from 1 to 5 (default PHP font, the bigger the numb, the bigger the font size) or a system font
  • x: horizontal shift (coordinate)
  • y: vertical shift (coordinate)
  • string: text to be written
  • color: variable with the allocated color

Note that the x and y coordinates are relative to the top left of the image. Also, for this example we will be using the default PHP font, but generally any TTF font will do, as i'll describe towards the end of the article.

This is our base image:

Basically, I'll write my name in the reserved spot, taking all this into account I can calculate the coordinates removing 2 or 3 pixels from the top because of the font overhead. The text should also be urldecoded and then on to the function that looks like this:

PHP:
  1. imagestring( $rImg,5,126,22,urldecode($_GET['nome']),$cor );

Before we finish up we have to define our content-header indicatig that our content is a JPG image, and then we can output the image code using the imageJPEG, that will spit out our raw image code. This function can also receive a second parameter that will output the content into the indicated file.

PHP:
  1. header('Content-type: image/jpeg');
  2. imagejpeg($rImg);

This is the final result:

And this is the final code:

PHP:
  1. &lt;?php
  2.  
  3. //Carregar imagem
  4. $rImg = ImageCreateFromJPEG("ex-img.jpg");
  5.  
  6. //Definir cor
  7. $cor = imagecolorallocate($rImg, 0, 0, 0);
  8.  
  9. //Escrever nome
  10. imagestring($rImg,5,126,22,urldecode($_GET['nome']),$cor);
  11.  
  12. //Header e output
  13. header('Content-type: image/jpeg');
  14. imagejpeg($rImg,NULL,100);
  15.  
  16. ?&gt;

Using custom fonts

We can use custom fonts to write our text, like Arial, Verdana or even more exotic ones like Futura or any other font not present by default in typical systems.To use TrueType fonts we can use the imagettftext function that allows us to point a .ttf file of the font we wish to use, as we can see jus below:

PHP:
  1. $font = 'arial.ttf';
  2. imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

1 Star2 Stars3 Stars4 Stars5 Stars (3 votos, média: 3.33 de 5)
Loading ... Loading ...

3 Comments »

March 13th 2007

Optimizing code with __autoload()

With the advent of PHP5 a new tool was available to all who wished to optimize their code, its called __autoload. This function can reduce the time lost by having to include object and class files in your code. But how do you proceed in creating an __autoload function to optimize code?
Continue Reading »

1 Star2 Stars3 Stars4 Stars5 Stars (Sem votos registrados)
Loading ... Loading ...

No Comments yet »

October 2nd 2006

dmsAutoComplete v1.1 - ChangeLog

Recently I published an updated version of my auto-complete (Google suggest) script compatible with IE and FireFox and based on PHP/AJAX.

After publishing version 1.0, I had some feedback from people who downloaded an tested it, so now I decided to correct some of the bugs that were found, and make a few improvements also. So now I’m going to publish version 1.1, check out some of the changes I made. Continue Reading »

1 Star2 Stars3 Stars4 Stars5 Stars (1 votos, média: 5 de 5)
Loading ... Loading ...

4 Comments »

September 18th 2006

A study on RSS - Part 2: The RSS format

In the last article I made a simple introduction to what is an RSS Feed and showed the path to creating XML files in PHP. Now it’s time to explain the RSS file structure along with some basic history.
Continue Reading »

1 Star2 Stars3 Stars4 Stars5 Stars (2 votos, média: 5 de 5)
Loading ... Loading ...

1 Comment »

September 15th 2006

strtotime() - is it useful?

Every now and then I get e-mails with questions that ask “How can I add X days to a given date?”, “How can I figure the day that corresponds to next thursday?”, and others along the same line. It scares me when I see replies that include enormous codes that execute innumerous function even including some bizarre leap year determination algorithms, I just can’t understand why all the complication and fuss.

The strtotime() function exists to solve these problems and i plan to introduce you to it and show a few usage examples. Also I’m going to check function performance using a simples benchmark comparison. Continue Reading »


1 Star2 Stars3 Stars4 Stars5 Stars (4 votos, média: 5 de 5)
Loading ... Loading ...

2 Comments »

September 1st 2006

WP Widget: BlogBlogs.com.br Favorites

After BlogBlogs released its public API, it became possible to develop plug-ins that used their data to display different information on our blogs. Using this widget its possible to retrieve you favorite blogs list, and keep it synchronized always. Continue Reading »

1 Star2 Stars3 Stars4 Stars5 Stars (5 votos, média: 4 de 5)
Loading ... Loading ...

3 Comments »

July 16th 2006

Developing an auto-complete script with AJAX/PHP

Working on on Management system for the Comercial department I received innumerous requests saying “but can’t you show me the client’s name as I type here?”. Well I wish the words were as poetica as those but what really happened is that they were mixing up the registered clients with IE auto-complete feature, well you know, users will be users.

So I was faced with a challenge, how could I solve the problem working is a web-based environment? I needed a script that would search the database in real time as I typed the actual words in the text box, and return to me the vendor related to that client. Well some time back thinking in web-based systems I would just claim “impossible! Dude, we are talking browser here, no some VB or deplhi program!”… not anymore! Hence xmlHttpRequest came into question and the new AJAX-way of working net content came into view.

So I begun my search for an “auto-complete” or “Google suggest” (yeah, when you are good I can create cool names uh?) script that would handle my needs. I found quite a bit each with a diferent solution but no AJAX integrated (except Google’s of course). I tried to get a clue from Google implementation, but trust me, when someone wants to make a javascript file look scrambled and illegible, well it is possible, and Google accomplished just that.

So I begun from the beginning as they say:

HTML:
  1. <input name="string" id="string" onkeyup="sendAjaxReq(this.value)" type="text" />

The idea was simple, with each keystrike an AJAX request is sent to a PHP script that is responsible for searching the database looking for the entries that begin with the string provided and returning a XML formatted list of results. Something like:

XML:
  1. <root>
  2. <item id="286" label="temos"></item>
  3. <item id="288" label="ter"></item>
  4. <item id="332" label="tecnol%F3gico%2C"></item>
  5. </root>

That was simple enough, just trigger a floating DIV and fill it with an unordered list (UL) and feed each result as a lit item (LI). So the basic was there, but you needed to grab the mouse and click on the choosen result when you found it, not that much fun…

It was missing something like Google used, that triggered the navigation through the results using the keyboard, up and down arrows to be exact. And also using the ENTER and TAB keys to select the result. So I based myself on another script I had checked out just to get a heading on which way to go.
So adding A plus B I finally finished the script, complete with AJAX, database search, keyboard and mouse navigation… the works. When it was done I found innumerous other applications for it, it seemed this kind of script can be applied in several situations, and make them much more user-friendly. So I decided to make the script more generic to make its distribution easier so I could shared it with all of you.

Live Demo: here
Download (with examples): dmsAutoComplete.zip

Hope it turns out to be of some use to any of you.

Known Bugs: In Firefox on the first list population run the UL appears as a single line, not breaking lines between choices.

1 Star2 Stars3 Stars4 Stars5 Stars (13 votos, média: 4.31 de 5)
Loading ... Loading ...

20 Comments »

July 15th 2006

A study on RSS - Part 1 XML DOM

RSS, today someone asked me, "what is this?"

Well, I know what it is, but at that moment the words failed me, especially the "non-programmer" words, so as to explain to "the common folk" the true meaning of it and some of its uses. So i decided to write this series of posts, don't know how many or which sequence I'll follow but i guarantee i will try to cover all the basics.

The wikipedia defines RSS as a xml specification of web feeds used for web syndication of site content.

"So what?" you say, WTF you exclaim!.. well let's take it in small steps..

XML is a web format largely used in web environments (technical information: used in general for encoding any structured data), a kind of global language defined for communication between sites, and systems. Being a standard means everyone understands its syntax, something like grammar i would say.

So that doesn't get you gears going? Guess you are not a developer, so I’ll explain what it's good for, but in case you are a developer, stick around and I’ll initiate the road to building a RSS Feed.

RSS is the "language" spoken by feeds, which are really like a summary of a site's contents (RSS - Rich Site Summary), it sends summarized data (title, description and link) of the site contents. For example, in the site ComuniWEB (Brazilian news site) where I’m currently employed the RSS feed dishes out the latest news published on the site. Considering this i ca use a "RSS Reader" and view the latest headlines, and in case any of them catches my eye, i just click on it and it sends me directly to the full story.

You can check out an example in the sidebar under the title "ComuniWeb - Últimas". This section reads the last 5 headlines from ComuniWEB.

Ok, so now you maybe understand a little bit more about RSS Feeds, go play around for a bit find a RSS Reader like Google Reader, try out a few feeds, you can even add them to personal sites like myYahoo.

Ok so you are a developer, you have a blog, a news site or some content you like to share? Want to know how to do it? Ok I’ll start you on your way. In today's post I’m going to start on the basics, creating a XML file from PHP data. In the next one I should get into the RSS file structure and then who knows? parsing RSS.

Fisrt Step:
XML Compatibility on PHP

PHP has a few options for reading and writing XML, from the bedrock basic direct string creation to solid objects like DOM. Well if i have to pick one, DOM is the winner, it's stable and has a simple but powerful logic, once you get the hold of it.

Let's create a file with the following structure

XML:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <news>
  3.   <item id="162696">
  4.     <title>Brazil loses the World Cup</title>
  5.     <link>index.php?idpag=20&amp;idmat=162696</link>
  6.   </item>
  7. </news>

First we need to create a new XML Doc via DOM

PHP:
  1. $xmlDoc = new DOMDocument('1.0', 'utf-8');
  2. $xmlDoc->formatOutput = true;

Now the $xmlDoc variable contains a DOM Object instance and using the "formatOutput" function we tell it to come out tidy-looking. Next we will create the root element, called "news" in the example:

PHP:
  1. $news = $xmlDoc->createElement('news');
  2. $news = $xmlDoc->appendChild($news);

In the fist line we create a element called news from the main XML Doc, it has no content. In the second line we attach that new node to the root node, sending it back to a $news variable so as to have a up-to-date reference to the node.

Now we need to create an item node with the attribute "id", check it out:

PHP:
  1. $item = $xmlDoc->createElement('item');
  2. $item->setAttribute('id','162696');
  3. $item = $news->appendChild($item);

Once more we create a node, always from the root Doc. Next we set the value of the attribute and its name. In the following line we connect it to the parent node, in this case $news, noticed the difference? This means the item node is now a child of the news node created before.

Now we simply add the Title and the Link nodes to the item node finalizing the addition process, but notice the slight difference here:

PHP:
  1. $title = $xmlDoc->createElement('title',utf8_encode('Brazil loses the World Cup'));
  2. $title = $item->appendChild($title);
  3.  
  4. $link = $xmlDoc->createElement('link',htmlentities('index.php?idpag=20&amp;idmat=162696'));
  5. $link = $item->appendChild($link);