Login

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.

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.

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.

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.

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.

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.

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.

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.

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).

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.

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.