MySQL
  Home arrow MySQL arrow Creating An Online Photo Album with PHP an...
IBM Rational Software Development Conference
Iron Speed
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Download TestComplete 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
MYSQL

Creating An Online Photo Album with PHP and GD: Part 1
By: Frank Manno
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 30
    2003-08-28

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    Iron Speed
     
    ADVERTISEMENT

    Ajax Application Generator Generate database and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!

    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,

    “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 800x600, although, 1024x768 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.

    [/Note]

    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.
     
        /*****
        * 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;
        }

    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]

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

    $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);

    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.

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


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More MySQL Articles
    More By Frank Manno

     

    IBM® developerWorks developerWorks - FREE Tools!


    Be the first to hear about i5/OS V6R1!

    Hold your calendar on January 30, 2008 for this free webcast on the new i5/OS. Rational's Enterprise Modernization products will be discussed at this webcast as they help to drive the application development environment for this new System i OS. <br />And learn how i5/OS will take you to the next step of efficient, resilient business processing. You will hear about the new i5/OS capabilities as it will be the most significant i5/OS release in years. If you cannot join the webcast on 1/30/08 you can still use this link to listen to the replay.<br />
    FREE! Go There Now!


    IBM – Taking Web 2.0 to Work

    You'll get answers to many questions and more from David Barnes, Lead Evangelist for IBM Emerging Internet Technologies. David will discuss aspects of Web 2.0 that bring value to corporations, academia, and government. He'll also discuss IBM's vision around Web 2.0, including the importance of remixability and consumability. The discussion will culminate with examples of various IBM Software Group solutions you can use to get ahead of the Web 2.0 adoption curve.
    FREE! Go There Now!


    NEW! Build Web services with transport-level security using Rational Application Developer V7, Part 1: Build Web services and Web services clients

    Build secure Web services with transport-level security using IBM Rational Application Developer V7 and IBM WebSphere Application Server V6.1. Follow this three-part series for step-by-step instructions about how to develop Web services and clients, configure HTTP basic authentication, and configure HTTP over SSL (HTTPS). This first part of the series walks you through building a Web service for a simple calculator application. You generate and test two different types of Web services clients: a Java Platform, Enterprise Edition (Java EE) client and a stand-alone Java client. You also handle user-defined exceptions in Web services.
    FREE! Go There Now!


    NEW! Demystifying the automation of custom controls: Part 2. A step-by-step example of using IBM Rational Functional Tester to automate custom controls

    This tutorial applies the concepts that were covered in the first part of this two-part series to a real-world example.
    FREE! Go There Now!


    NEW! Download DB2 9.5 for Linux, Unix, and Windows

    Download a free trial version of IBM DB2 9.5 for Linux, UNIX, and Windows. DB2 9 is the result of a five-year development project that transformed traditional (static) database technology into an interactive data server that merges the high performance and ease of use of DB2 with the self-describing benefits of XML.
    FREE! Go There Now!


    NEW! Hello World: Monitor a simple business process using WebSphere Business Monitor V6.0.2

    This tutorial shows new users of IBM WebSphere Business Monitor Version 6.0.2 how to perform the "Hello World" equivalent for monitoring business process applications. It is intended to help you get familiar with the capabilities of the product.
    FREE! Go There Now!


    NEW! Integrating XML into Your Enterprise Using Data Federation

    XML has become a common way of storing business data as flat files and many data server vendors including IBM have provided ways to store this data within relational database systems. Increasingly collections of XML files are accessed like databases using an xQuery and other XML standard mechanisms. Businesses find the need to combine the traditional tabular structured data with XML formatted data. In this webcast, you’ll learn about IBM’s WebSphere Federation Server technology, which provides users with the ability to integrate these two data formats.
    FREE! Go There Now!


    NEW! Rational 'Talks to You' Teleconference Series

    This Fall, IBM Rational talks to you directly through a special teleconference series giving you access to the best minds in IBM Rational - product experts and market thought leaders who will answer your questions during these pre-scheduled telephone conference calls. Register today!
    FREE! Go There Now!


    NEW! Rational Testing eKits

    Discover how Rational tools and best practices for testing can make your job easier. The new Rational Testing eKits provide you with valuable resources – including demos, webcasts, tutorials, and articles – that help you address your specific testing needs across the software lifecycle. Five new eKits are available covering the topics of Requirements and Test Management, Functional Testing, Performance Testing, Code Quality and Embedded Systems, and SOA and Web Services Testing.
    FREE! Go There Now!


    NEW! Webcast: What is new in Viper 2 for developers?

    Viper 2 brings a great value to developer communities including SQL, XML, PHP, Ruby, .NET and Java. You probably already know that DB2 Express-C is free for developers to develop, deploy and distribute. Viper 2 provides a variety of means that help move your application from the development stage to deployment more rapidly. This webcast shows how to best utilize the latest tools available for developing DB2 applications.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    MYSQL ARTICLES

    - MySQL and BLOBs
    - Two Lessons in ASP and MySQL
    - Lord Of The Strings Part 2
    - Lord Of The Strings Part 1
    - Importing Data into MySQL with Navicat
    - Building a Sustainable Web Site
    - Creating An Online Photo Album with PHP and ...
    - Creating An Online Photo Album with PHP and ...
    - PhpED 3.2 – More Features Than You Can Poke ...
    - Creating An Online Photo Album with PHP and ...
    - Creating An Online Photo Album with PHP and ...
    - Security and Sessions in PHP
    - Setup Your Personal Reminder System Using PHP
    - Create a IP-Country Database Using PERL and ...
    - Developing a Dynamic Document Search in PHP ...






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway