Online Photo Album Development using PHP and GD: Part 1

This article is the first part of a four part series about saving money and space when it comes to showing off your pictures. Frank will be using PHP, MySQL and GD in this series.

You know the feeling. You come home with a brand new digital camera or scanner, and immediately want to show off your work! I’ve been there. I purchased a Fuji digital camera last year and found myself snapping pictures of anything and everything; and trust me, sometimes I wonder why I bother taking pictures! :) The benefit of going digital, as we all know, is there are no expensive costs for film, no wasted photos, and no under/over exposed pictures.

So what’s the disadvantage of digital? Unless you print every photo taken, or unless you have everybody hovering over your shoulder while you show them pictures from your computer, there really is no economic way of showcasing your photos. You could sit there and email your shots, which would seem like the better choice; but, eventually, either your bandwidth costs will increase, or upset family members will be calling you complaining about the abundance of large-sized emails they’ve been receiving from you! :)

There are many services available out there that allow you to upload your favourite photos, and display them in a personalized gallery for viewing online. While the costs associated can vary (in my experiences, prices I’ve found have ranged from $4 to $20 per month).

There’s nothing more fulfilling than creating your very own customized online photo gallery. The added bonus is that your viewers don’t have to navigate to another website to view your photos. By creating your own gallery, your visitors can view your artistic pieces directly from your already existing website.

You may be asking yourself,

{mospagebreak title=Photo Sizing}

“Why would I upload an overly-sized photo that would span longer than the average screen resolution?”

Well, the answer is simple: by making use of GD and PHP, you can create a gallery that will not only eliminate the hassle of resizing your photos, you will also be able to provide thumbnail images so that you can view a smaller-sized version prior to clicking on the higher-quality image, thus saving your bandwidth and your insanity!

For this small project, we’re going to make use of PHP, MySQL, and GD, all of which are freely available for download. I am also going to introduce a thumbnail-making class file, which will be easily reusable in any other of your future projects.

Welcome Class – It’s Thumbnail Time!

First things first, we’ll start by coding our thumbnail class – which I’ve dubbed GallerySizer. One of the first things we need to figure out is how big we want our full-sized images to be. For the most part, the standard resolution is roughly 800×600, although, 1024×768 is slowly becoming the norm. Nonetheless, we’re better off catering to those with smaller screens, so that they can experience the full effect of your photos.

// Define script constants
DEFINE(“IMAGE_BASE”, ‘../photos/’);
DEFINE(“THUMB_BASE”, ‘../thumbs/’);
DEFINE(“MAX_WIDTH”, 100);
DEFINE(“MAX_HEIGHT”, 100);
DEFINE(“RESIZE_WIDTH”, 800);
DEFINE(“RESIZE_HEIGHT”, 600);

The lines above simply define constant variables that will be used throughout our GallerySizer class. The beauty behind constants, is that because their values never change throughout the class, we can simply define them at the top of the class. If we decide we want the values to change, we need only to change the values in the one location, and the changes will take effect throughout the rest of the code.

We first start by defining out IMAGE_BASE constant, which is the directory location where our re-sized images will be stored for viewing. The THUMB_BASE directory is the location that will store our thumbnails. MAX_WIDTH and MAX_HEIGHT define the maximum width and height of our re-sized images, respectively.

Note:

In case you’re wondering, I’ve decided not to store the actual images inside a database. It’s a discussion that is brought up regularly in our forums, and to be honest, I prefer to store the images in a directory, while storing the path to the actual image in the database table. There are pros and cons to each method, but for reasons related to the speed of the database, we’ll store the path in our tables. We’ll discuss our database structure later on.

{mospagebreak title=Photo Class}

Next we define our class:

class GallerySizer{
var $img; // Original image file object
var $thumb; // Thumbnail file object
var $resize; // Resized image file name
var $width; // Original image width
var $height; // Original image height
var $new_width; // Resized image width
var $new_height; // Resized image height
var $image_path; // Path to image
var $thumbscale; // Scale to resize thumbnail
var $image_file; // Resized image filename
var $thumbnail; // Thumbnail image file object
var $random_file; // Resized image file name (random)

To define a class file, you simply use the keyword class followed by the class name; in our case, GallerySizer. The convention behind class names is to capitalize the first letter of the class name, followed by capitalizing the first letter of every following word without underscores or dashes (ie: GallerySizer and not Gallery_Sizer).

The variables we’ve created are known as member data, when discussing them in terns of Object Oriented Programming (OOP). These variables are global to the class, which will allow any method (function) to access them. They are used throughout the script for various functions, including creating the thumbnail, determining the resizable scale for the new images, creating a random filename for the newly converted images, etc.

/*****
* Retrieves path to uploaded image.
* Retrieves filename of uploaded image
*/
function getLocation($image){
$this->image_file = str_replace(“..”, “/”, $image);
$this->image_path = IMAGE_BASE . $this->image_file;
return true;
}

The method above, getLocation($image), accepts an image as its argument. The image will be passed from the upload form to the method, which will then initialize the $image_file variable to hold the name of the image, and the $image_path variable to hold the path to where the resized image will reside on the server.

[code]/*****
* Determines image type, and creates an image object
*/
function loadImage(){
$this->img = null;
$extension = strtolower(end(explode('.', $this->image_path)));
if ($extension == 'jpg' || $extension == 'jpeg'){
$this->img = imagecreatefromjpeg($this->image_path);
} else if ($extension == 'png'){
$this->img = imagecreatefrompng($this->image_path);
} else {
return false;
}
// Sets a random name for the image based on the extension type
$file_name = strtolower(current(explode('.', $this->image_file)));
$this->random_file = $file_name . $this->getRandom() . "." . $extension;
$this->thumbnail = $this->random_file;
$this->converted = $this->random_file;
$this->resize = $this->random_file;
return true;
}[/code]

The loadImage() function above determines the file-type of the current image by splitting the filename into an array, split by the dot (.) in its name, using PHP’s explode() function. The end() function simply retrieves the last element in the array.

Based on the image type, we call the “imagecreatefromXXXX” function, which, in the case of a JPEG, returns a pointer to a true-color image. This pointer is used later on the code to create our resized and thumbnail images.

To ensure that every image uploaded is unique, we retrieve the name of the image (less the extension), and add a random value to the image name. In this case, our getRandom() function will return the current date/time value, which will then be appended to the filename, creating a unique name.

[Note]

{mospagebreak title=To Gif or Not to Gif} In earlier versions of GD, multiple image types were supported, including GIF, JPEG, PNG, and others. Due to patents held by the Unisys LZW group, GIF support has been discontinued in order to keep GD a free product. However, for those of you who are looking for GIF conversion support, the GD website states that GIF support will be reappear in June 2004; the date in which the patent will expire world-wide:

Many have asked whether gd will support creating GIF files again, since we have passed June 20th, 2003, when the well-known Unisys LZW patent expired in the US. Although this patent has expired in the United States, this patent does not expire for another year in the rest of the world. Since I have no way of limiting distribution of GIF-creating code to US users only that is guaranteed to please somebody else’s lawyer, I have opted to follow the same policy that the ImageMagick authors are following: GIF creation will not reappear in GD until the patent expires world-wide on July 7th, 2004. I realize this situation is frustrating for many; please direct your anger and complaints toward the questionable patent system that allows the patenting of such straightforward algorithms in the first place. Thank you!

GD version 2.x supports image conversion for JPEG, PNG, and WBMP. WBMP is supported by wireless browsers. For this article, however, we’ll focus primarily on JPEG and PNG image formats. Adding support for WBMP images is as easy as adding in calls to the GD functions which support conversion for WBMP files.

[/Note]

/*****
* Retrieves size of original image. Sets the conversion scale for both * the thumbnail and resized image
*/
function getSize(){
if ($this->img){
$this->width = imagesx($this->img);
$this->height = imagesy($this->img);
$this->thumbscale = min(MAX_WIDTH / $this->width, MAX_HEIGHT / $this->height);
} else {
return false;
}
return true;
}

The getSize() function uses GD’s imagesx() and imagesy() functions to retrieve the width and height of the image. We then perform a division calculation to determine the scale for the thumbnail images:

min(MAX_WIDTH / $this->width, MAX_HEIGHT / $this->height);

PHP’s min() function returns the lowest value of all arguments passed to it. By performing a min() calculation, we are able to determine the scaling ratio used to resize our image. We use the lowest value of the two arguments to maintain the aspect ratio when reducing the image size; otherwise, we would end up with a distorted image.


/*****
* Creates a thumbnail image from the original uploaded image
*/
function setThumbnail(){
// Check if image is larger than max size
if ($this->thumbscale < 1){
$this->new_width = floor($this->thumbscale * $this->width);
$this->new_height = floor($this->thumbscale * $this->height);
// Create temp image
$tmp_img = imagecreatetruecolor($this->new_width, $this->new_height);
// Copy and resize old image into new
imagecopyresampled($tmp_img, $this->img, 0, 0, 0, 0, $this->new_width, $this->new_height, $this->width, $this->height);
$this->thumb = $tmp_img;
}
return true;
}

The setThumbnail() function first checks to see if the thumbscale (set by the getSize() function), is less than 1. If the scale is larger than 1, the original image is less than the desired thumbnail size, and this function is skipped completely. If, however, the scale is less than 1, we resize the image to the desired thumbnail size (in this case 100×100). Remember, however, that since we took the lower of the two values when determining the conversion scale, GD will resize the thumbnail appropriately, so the image won’t actually be 100×100.

$this->new_width = floor($this->thumbscale * $this->width); $this->new_height = floor($this->thumbscale * $this->height);

By using the thumbscale variable, we can determine the exact size to use when creating our thumbnail. This will maintain the aspect ratio of our image.

// Create temp image
$tmp_img = imagecreatetruecolor($this->new_width, $this->new_height);

imagecreatetruecolor() creates a pointer to a true-color image, set the size of our thumbnail’s dimensions, calculated above.

imagecopyresampled($tmp_img, $this->img, 0, 0, 0, 0, $this->new_width, $this->new_height, $this->width, $this->height);
$this->thumb = $tmp_img;

We then call imagecopyresampled() passing to it the $tmp_img pointer, the original image, as well as the following:

0 –> Starting x co-ordinate of the destination image (thumbnail)
0 –> Starting y co-ordinate of the destination image (thumbnail)
0 –> Starting x co-ordinate of the source image
0 –> Starting y co-ordinate of the source image
$this->new_width –> Width of the thumbnail
$this->new_height –> Height of the thumbnail
$this->width –> Width of the source image
$this->height –> Height of the source image

We then assign the temporary image ($tmp_image) to our thumbnail object ($this->thumb).

/*****
* Resizes uploaded image to desired viewing size
*/
function resizeImage(){
if ($this->width < RESIZE_WIDTH){
$this->resize = $this->img;
return true;
} else {
// Create re-sized image
$tmp_resize = imagecreatetruecolor(RESIZE_WIDTH, RESIZE_HEIGHT);
// Copy and resize image
imagecopyresized($tmp_resize, $this->img, 0, 0, 0, 0, RESIZE_WIDTH, RESIZE_HEIGHT, $this->width, $this->height);
imagedestroy($this->img);
$this->resize = $tmp_resize;
return true;
}
}

resizeImage() does just that. We will perform the resizing of the original image to the specified width and height specified in our defined constants. We first check to see if it is necessary to resize the image. Because there is the possibility that an image may be longer than it is wide, and still be less than our desired RESIZE_WIDTH (ie: 800px). We verify to see if this is so, and simply use the existing image.

If the image is larger than the desired width, we’ll resize it:

$tmp_resize = imagecreatetruecolor(RESIZE_WIDTH, RESIZE_HEIGHT);

{mospagebreak title=Resizing Images} Again, we make use of GD’s imagecreatetruecolor() to create a pointer to a true-colored image.

imagecopyresampled($tmp_resize, $this->img, 0, 0, 0, 0, RESIZE_WIDTH, RESIZE_HEIGHT, $this->width, $this->height);
imagedestroy($this->img);
$this->resize = $tmp_resize;

We then resize our image to the specified size, passing to it the temporary image pointer, the original image, and the 4 parameters dealing with the co-ordinates and size (similar to the ones passed in the setThumbnail() function.

GD has a built-in function to destroy the original image uploaded. We’ll use this function once our image has been resized, followed by assigning the value of $tmp_resize, to our resized image object ($this->resize).

/*****
* Copies thumbnail image to specified thumbnail directory.
* Sets permissions on file
*/
function copyThumbImage(){
imagejpeg($this->thumb, $this->thumbnail);
if(!@copy($this->thumbnail, THUMB_BASE . $this->thumbnail)){
echo(“Error processing file… Please try again!”);
return false;
}
if(!@chmod($this->thumbnail, 666)){
echo(“Error processing file… Please try again!”);
return false;
}
if(!@unlink($this->thumbnail)){
echo(“Error processing file… Please try again!”);
return false;
}
return true;
}

Because we’re not storing our images in a database, we need to copy the file over to our new images to our desired directories, specified in our constant variables.

imagejpeg($this->thumb, $this->thumbnail);

The imagejpeg() function will actually write the JPEG file information to a file that will now reside in the filesystem. We pass, as arguments, the thumbnail pointer ($this->thumb) and the object which will represent the actual thumbnail file ($this->thumbnail).

We then copy the image to our thumbnail directory, set the desired permissions (making use of PHP’s chmod() function), and unlink/delete the temporary thumbnail image.

/*****
* Copies the resized image to the specified images directory.
* Sets permissions on file.
*/
function copyResizedImage(){
imagejpeg($this->resize, $this->converted);
if(!@copy($this->converted, IMAGE_BASE . $this->converted)){
echo(“Error processing file… Please try again!”);
return false;
}
if(!@chmod($this->converted, 666)){
echo(“Error processing file… Please try again!”);
return false;
}
if(!unlink($this->converted)){
echo(“Error processing file… Please try again!”);
return false;
}
// Delete the original uploaded image
if(!unlink(IMAGE_BASE . $this->image_file)){
echo(“Error processing file… Please try again!”);
return false;
}
return true;
}

Our copyResizedImage() function is identical to the copyThumbImage() function, except that we work with the resized image rather than the thumbnail.

/*****
* Generates a random number. Random number is used to rename
* the original uploaded image, once resized.
*/
function getRandom(){
return “_” . date(“dmy_His”);
}

Our getRandom() function simply returns a string value with the current date and time with a seconds value.

/*****
* Returns path to thumbnail image
*/
function getThumbLocation(){
return “thumbs/” . $this->random_file;
}

The getThumbLocation() function returns the path to our thumbnail image, so that the value may be inserted into our database for retrieval later on.

/*****
* Returns path to resized image
*/
function getImageLocation(){
return “photos/” . $this->random_file;
}

The getImageLocation() returns the path to our resized image, which will be inserted into our database for retrieval later on.

{mospagebreak title=Conclusion} Database Snapshots

We need to create our database structure. We have many options available to us regarding how we want our images to be organized. I’ve chosen to go with creating multiple albums, containing multiple images. This will allow for a well-organized gallery, in that we can group related albums together.

Our database structure will contain the following tables:

Table Name: album

Table Name: photo

We’ll now create our tables using MySQL:

CREATE TABLE album (
album_id int(11) NOT NULL auto_increment,
album_name varchar(255) NOT NULL default ”,
album_desc text NOT NULL,
album_cover varchar(255) NOT NULL default ”,
PRIMARY KEY (album_id),
KEY album_name (album_name)
) TYPE=MyISAM;

CREATE TABLE photo (
photo_id int(11) NOT NULL auto_increment,
photo_title varchar(255) NOT NULL default ”,
photo_desc text NOT NULL,
photo_date datetime NOT NULL default ‘0000-00-00 00:00:00′,
photo_location varchar(255) NOT NULL default ”,
thumbnail_location varchar(255) NOT NULL default ”,
album_id int(11) NOT NULL default ‘0’,
PRIMARY KEY (photo_id),
KEY photo_title (photo_title),
) TYPE=MyISAM;

An example INSERT query may be something like the following:

INSERT INTO album VALUES(0, ‘Frank’s Birthday’, ‘May contain incriminating photos! :)’, ‘thumbs/at_the_bar_080103_180743′);

INSERT INTO photo VALUES(0, ‘1st Drink of Many’, ‘A Drink with Friends!’, ‘2003-08-03 18:07:43′, ‘photos/ at_the_bar_080103_180743′, ‘thumbs/ at_the_bar_080103_180743”, 1);

Now that our tables have been created, we can worry about the structure of our “back-end interface”, which will allow us to upload our images into the chosen album(s).

[gp-comments width="770" linklove="off" ]

chat