Showing posts with label Technology. Show all posts

Create your own 3D (Anaglyph) glasses

by Lasantha Samarakoon on Thursday, August 5, 2010

I’m going to deviate from my usual topics today. Let’s consider a small topic in Multimedia. Did you ever tried to create your own 3D glasses for watching 3D movie? If not, today I’m going to tell those steps. If you are not preferred you can buy one around US$ 1 on eBay. But remember, this is so easy and you can create your own one within 15 minutes.

Anaglyph Glass

Before directly jump to our steps, let’s get an idea about this 3D glasses?

There are some videos and images, which provide stereoscopic 3D effect. Our naked eyes are not capable of capturing this effect 100%. So we need to use special glasses called, 3D glasses or “Anaglyph glasses” to help our brains to understand the effect. These anaglyph images/videos are made up of 2 colored layers, offset with respect to each others, which helps to produce the depth effect.

Sample anaglyph image from Wikipedia (Author: Richard Bartz)

Okay, that’s little bit about the concept. Now it’s working time. Here are the materials we need:

  • Card board
  • Template for the glasses. A sketch is available here and you need to have a print out of it. Or else, you can draw your own one too.
  • Red and Cyan (Blue) cellophane papers.
  • And finally the hardest thing, Glue...

Here are the steps:

  1. Cutout the template on the cardboard using the printed (or drawn) sketch.
  2. Cut the cellophane to fit the holes in the template.
  3. Glue or tape them to the holes in the template.  (And make sure you put Red cellophane for the left eye and the cyan cellophane for the right eye.)
  4. Now it’s finished creating your own 3D glasses. Enjoy 3D movies and images using your new 3D glasses.

Watch sample 3D video at http://www.youtube.com/watch?v=-RKI0mtedZw

CSS Typography: Using "font-face"

by Lasantha Samarakoon on Thursday, March 4, 2010

One of the main issues involved with web designing is using proper fonts for the interface. That is because in most of times matching fonts for the user interface design are not standard web fonts. Therefore all the users must have the font to view the web properly. Otherwise the default fonts will be displayed.

There are some alternatives to overcome this issue. One of them is using images instead of text. So the images are rendered with the original font, and that will solve our problem. But it is also not issue free. These are the main issues with it.

Images consume more bandwidth than text. Hence it consumes time also.

Search engines are less sensitive for images. They can’t read the content of image and therefore Search Engine Optimization (SEO) will be an issue too.

Hence images are not the best option. There is another alternative, i.e. using CSS font-face. Font-face is used to define fonts in a style sheet.

@font-face {
      font-family: Bambino;
      src: local("Bambino"), url("Bambino.ttf") format("opentype");
}

Here, you can specify the source (src) of the font. local means if the font defined is available in the local PC, then use it. url means if it is not, download it from the given location. Let’s see how this can use.

/* 
      file: styles.css 
      "Bambino" is the font I used. "Bambino.ttf" is the relevent font file.
*/

@font-face {
      font-family: Bambino;
      src: local("Bambino"), url("Bambino.ttf") format("opentype");
}

h1 {
      font: bold 28px Bambino;
}

p {
      font: 18px Bambino;
}

<!-- file: font.html -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CSS Typography</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>

<body>

<h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit</h1>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras bibendum dui id arcu ornare eu lobortis orci bibendum. Mauris rhoncus tincidunt vestibulum. Duis imperdiet neque sed turpis viverra suscipit gravida est varius. Nullam euismod tellus quis velit semper vitae vehicula ligula congue.</p>

</body>
</html>

Dynamic progress bar with PHP GD

by Lasantha Samarakoon on Wednesday, February 24, 2010

Today I’m going to show you something regarding GD library of PHP. The GD library is the main library using for Graphics in PHP. By using functions of this library, it is possible to manipulate images with PHP.

In this post, I will show you how to create a dynamic progress bar with PHP. In here the “dynamic” means you can parse 2 values, (i.e. maximum value and the current value) and the PHP script will calculate and render the progress bar dynamically on the screen. The output will come in the format of PNG image file. Hence it is very easy to use in you HTML file.

That’s all about the explanation. So let’s go for codes…

<?php
// filename: progressbar.php
// author  : lasantha samarakoon

// set the type of data (Content-Type) to PNG image
header("Content-Type: image/png");

// extract GET global array
extract($_GET);

// set defaults
if(! isset($max)) $max = 100;
if(! isset($val)) $val = 100;

// this method prepare blank true color image with given width and height
$im = imagecreatetruecolor(400, 20);

// set background color (light-blue)
$c_bg = imagecolorallocate($im, 222, 236, 247);
// set foreground color (dark-blue)
$c_fg = imagecolorallocate($im, 27, 120, 179);

// calculate the width of bar indicator
$val_w = round(($val * 397) / $max);

// create a rectangle for background and append to the image
imagefilledrectangle($im, 0, 0, 400, 20, $c_bg);
// create a rectangle for the indicator and appent to the image
imagefilledrectangle($im, 2, 2, $val_w, 17, $c_fg);

// render the image as a PNG
imagepng($im);

// finally destroy image resources
imagedestroy($im);
?>

OK… that is the PHP script. Now it’s time to display it in the browser. First create a HTML file to display the image. In the IMG tag of the HTML file, type the location of your PHP script and specify 2 values, maximum and current as follows.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Progress Bar</title>
</head>

<body>
 
    <img src="progressbar.php?max=100&val=70" />
 
</body>
</html>

That’s all, and you can see the output…

PEAR: An Introduction...

by Lasantha Samarakoon on Saturday, November 21, 2009

Today I’m gonna say you about something popular among the PHP developers. So that’s called PEAR. I hope you guys may be heard about PEAR. PEAR is an acronym for PHP Extension and Application Repository. PEAR is a framework or collection of PHP classes which allow us to use them in our solutions. Official web site of PEAR can be found on http://pear.php.net.

As I told you that PEAR is a collection of classes or components. So what are the components available in PEAR?  It has many more components such as Database, File system, Graphics and Image Processing, Mail, Math, Structures and etc. So today I’m going to show you how to use Database component of PEAR.

PEAR Database:

In most of web developing solutions, PHP developers use databases to store data. So the backend database management system can be MySQL, PostgreSQL, SQLite, etc. There are different commands available in PHP to handle each and every database types. What will happen when you want to shift from MySQL to PgSQL? This will result you to change all the PHP MySQL commands to PHP PgSQL commands. In this kind of changing environment, it is advisable to use a framework such as PEAR.

Using PEAR, you can handle many DBMSs without changing the code. It is something like a common API set. The only part you have to change when you want to shift is the connection string.

OK… Let’s consider about the example. In this example, I will connect to a MySQL database, fetch some data and display them on the web page. First you need to create the database as follows.

CREATE DATABASE test;
USE DATABASE test;
CREATE TABLE users(
    uname VARCHAR(20) NOT NULL,
    pword VARCHAR(20) NOT NULL
);

That’s all. Then the PHP code is as follows. I’ll explain them later.

<?php
// peardb_ex.php
require_once 'DB.php';

// connect to the database
$db = DB::connect('mysql://root:rootpass@localhost/test');

// check for errors
if(DB::isError($db)) {
    echo "Unable to connect to the database: " . $db->getMessage();
}else {

    // execute the query
    $sql = "select * from users";
    $res = $db->query($sql);

    // get number of rows affected
    $num_res = $res->numRows();

    echo "<b>$num_res users</b><hr /><hr />";

    // travers the resultset
    while($r = $res->fetchRow(DB_FETCHMODE_ASSOC)) {

        echo "username: " . $r['uname'] . "<br />";
        echo "password: " . $r['pword'] . "<br />";
        echo "<hr />";
    }

    // free resultset
    $res->free();

    // close the connection
    $db->disconnect();
}
require_once 'DB.php';

This is the file that has definitons for PEAR database component. It's available in the PEAR installation folder, so you need not to copy it to the local directory.

$db = DB::connect('mysql://root:rootpass@localhost/test');

This is how the connection will be established. The connection string can be specify as, Driver://username:password@host/database. If you want to shift from MySQL to PgSQL, the only thing you need to do is change the connection string to, pgsql://root:rootpass@localhost/test. Other commands will remain unchanged.

DB::isError($db);
This is used to check if any error occurred.
$sql = "select * from users";
$res = $db->query($sql);

This is the command used to execute SQL query against the database. (Same like $res = mysql_query($sql))

$num_res = $res->numRows();

Get number of rows returned by the query.

while($r = $res->fetchRow(DB_FETCHMODE_ASSOC)) {

    echo "username: " . $r['uname'] . "<br />";
    echo "password: " . $r['pword'] . "<br />";
    echo "<hr />";
}

This loop is used to travers the resultset. It is same as mysql_fetch_assoc($res).

$res->free();

Free the resultset.

$db->disconnect();

Close the connection.

AJAX File Download

by Lasantha Samarakoon on Sunday, November 15, 2009

Good day guys, today I’m going to show you how to download a file without reloading or refreshing the current page. So to do that, I will use my preferred server-side language PHP, HTML and little bit of CSS.

So the problem is, I have a link named “Download” and when I click on that link browser’s file download box should be visible without refreshing or navigating away from the page. So to solve this problem I will use an AJAX technique. Let’s think how we can implement this in AJAX.

My solution is this. I will create a HTML inner frame in my web page. And when I click on the download link, something will be loaded in the inner frame. So this is how I solved that.

I will create 2 web pages, one is pure HTML and other one is PHP. The HTML page contains the inner frame and download button. The PHP file is used to dynamically read the content of the downloadable file and write them to the client.

<!-- index.htm -->  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>AJAX Download</title>
</head>

<body>

<!-- this inner frame is hidden by css -->
<iframe name="ajax_frame" style="display: none;"></iframe>

<!-- download link -->
<a href="download.php" target="ajax_frame">Download</a>

</body>
</html>

Here I named inner frame as “ajax_frame” and in the link I set the target to that inner frame. So when I click on the link, the content will be loaded in the inner frame. And I set the display style of the inner frame to “none” to hide the frame in the web page. So the user cannot see the inner work of the web page.

<?php // download.php  
// send http header 'content-type'
header("Content-Type: text/plain");  

// start flushing data  
ob_start();  

// echo data  
echo "hello world";  

// get the flushed data size and send http header attribute 'content-length'  
header("Content-Length: " . ob_get_length());  

// send http header information regarding the file attachment  
header("Content-Disposition: attachment; filename=test.txt; modification-date=\"Sun, 15 Nov 2009 12:50:00 +0530\";");  
?>

Above is the technique I used to push the file content to the client. It’s just a PHP echo with some header commands. In this demonstration I did not used any external file, but I send some content using the echo command. This is really same as reading a text file contents “hello world” in it. Let’s consider line by line.

header("Content-Type: text/plain");

I used header command to send HTTP response headers to the client. Here I send “Content-Type” header indicating the incoming data is belongs to plain text. You can use any other Content-Type regarding to the data you are going to send. As an example, for a PDF file you can send “application/pdf”.

ob_start();
Start flushing data to the client.

echo "hello world";

Echo the content of the file.

header("Content-Length: " . ob_get_length());

Get the length of data flushed to the client and send the header “Content-Length” to the client.

header("Content-Disposition: attachment; filename=test.txt; modification-date=\"Sun, 15 Nov 2009 12:50:00 +0530\";");

Here it is again an HTTP response header, indicating that the flushed data belongs to the file named “test.txt” and the modified date of the file.

So this is all about the solution. If you want to send really an external file to the user, you have to replace line # 9 with commands regarding to open the file, read the content, echo the content and close the file. That’s all.