menu

Wednesday 26 February 2014

How to Generate Dynamic Favicon in PHP

please read about that Gmail has just launched small but really useful feature in Gmail Labs. Dynamic Favicon showing unread email counts directly in your browser tab icon. If your browser window has lots and lots of tabs open at anytime, this might be really a wonderful feature that lets user know of any unread item. Here is a small and powerful script in PHP that lets you create your own Dynamic favicon. We will use PHP GD library to manipulate the favicon image and add text into it. Below is the simple script that reads a favicon image add add some text character on it.
1<pre>
2//Read the favicon template from favicon.png
3//file from current directory
4$im = imagecreatefrompng("favicon.png");
5//$im = imagecreatefromjpg("favicon.jpg");   //using this function to load favicon of jpeg type
6//$im = imagecreatefrombmp("favicon.bmp"); //using this function to load favicon of bmp type
7  
8/* Read the character which needs to be added in favicon from
9 * get request
10 */
11if(isset($_GET['char']) && !empty($_GET['char'])) {
12    $string = $_GET['char'];
13} else {
14    /* If no character is specified; add some default value */
15    $string = 'V';
16}
17  
18/* background color for the favicon */
19$bg = imagecolorallocate($im, 255, 255, 255);
20  
21/* foreground (font) color for the favicon */
22$black = imagecolorallocate($im, 0, 0, 0);
23  
24/* Write the character in favicon
25 * arguements: image, fontsize, x-coordinate,
26 *              y-coordinate, characterstring, color
27 */
28imagechar($im, 2, 5, 1, $string, $black);
29  
30header('Content-type: image/png');
31  
32imagepng($im);
33 
34</pre>
The above code is pretty much self explanatory. We read a character from GET request and add it into the favicon image. Note here that we are using a template favicon image which me modify. You can place any favicon of your choice near favicon.php file.
 

No comments:

Post a Comment