Showing posts with label PHP. Show all posts

PHP Image Class

by Lasantha Samarakoon on Saturday, February 19, 2011

Today I am going to give you something that I have created using PHP. It is a simple PHP class that can be used to manipulate images easily in an object oriented way. I created this by using basic functions in PHP GD library.

Download

You can download the ZIP archive containing PHP classes by clicking here.

License

I would like to distribute this using GNU/GPL license, so you can add more functionality into it and enhance my basic product.

Functions

This class allows you to manipulate JPEG, GIF and PNG files. It allows image resizing, cropping, merging, rendering, saving and applying filters.

Documentation

Open image

new Image(path-to-file)

Example:

$img = new Image('/home/user/foo.jpg');

You can specify the relative or absolute path as the parameter. Note that this method may throw FileNotFoundException, whenever the method fails to locate the file on the target location.

Resize image

resize(width, height, [unit = ‘px’, [keep-aspect-ratio = false]])

Example:

$img->resize(800, 600, 'px', true);

Resize method allows you to resize image file. Unit can be either ‘px’ or ‘%’.

Crop image

crop(x, y, width, height)

Example:

$img->crop(100, 50, 600, 500);

Crop method allows cropping the image. It takes 4 parameters x coordinate, y coordinate, width and the height.

Merge images

merge(image-object, [x = 0, [y = 0, [opacity = 100]]])

Example:

$anotherImg = new Image('/home/user/bar.jpg');
$img->merge($anotherImg, 100, 100, 75);

Merge method can be used to merge to image objects. That means this method results merger of 2 images. Again it takes 4 parameters; Image object, x coordinate, y coordinate and opacity value. Opacity ranges from 0 to 100, which 0 means transparent and 100 means full opaque.

Save image

save(destination, [file-type = ‘jpg’])

Example:

$img->save('/home/user/foo_edit.png', 'png');

This class can be used to save the resulting image on a storage device. This requires a parameter ‘file-type’ which takes jpg, gif or png as values.

Render image

render([file-type = ‘jpg’])

Example:

$img->render('gif');

Render method allows rendering resulting image on the browser without saving it on a storage device. This requires a parameter ‘file-type’ which takes jpg, gif or png as values.

Filters

Available filters to apply on images are as follows.

  • negative()
  • grayscale()
  • detectEdges()
  • emboss()
  • gaussianBlur()
  • selectiveBlur()
  • brightness(value)
  • contrast(value)
  • colorize(r, g, b, [alpha = 0])
  • sketchy()
  • smooth(value)
  • sephia()

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.