MySQL
  Home arrow MySQL arrow Creating An Online Photo Album with PHP an...
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  
Mobile Linux 
App Generation ROI 
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 / 37
    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
     
     
    ADVERTISEMENT


    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!


    IBM DB2 Deep Compression ROI Tool

    The IBM DB2 Deep Compression ROI tool is designed for DBA’s and IT management personnel to perform a clinical analysis of the cost savings gained from the Storage Optimization feature of DB2 9 for Linux, UNIX and Windows. The feature, also known as Deep Compression, compresses data that lies within a database by up to 80% at times.
    FREE! Go There Now!


    NEW! Driving Business Success with Rational Process Library

    Join this webcast, to learn how the Rational Process Library can help with compliance issues, drive process improvement, and assist in service-oriented architecture (SOA) or Agile development. We will take a peek into the Rational Process Library with content around software and systems engineering (including RUP), operations and systems management, program and portfolio management, and asset and SOA governance.
    FREE! Go There Now!


    NEW! Download DB2 Express-C 9.5

    Visit IBM developerWorks to download IBM DB2 Express-C 9.5, a no-charge version of DB2 Express 9 database server. DB2 Express-C offers the same core data server base features as other DB2 Express editions and provides a solid base to build and deploy applications developed using C/C++, Java, .NET, PHP, and other programming languages.
    FREE! Go There Now!


    NEW! Download IBM Rational Developer for System z

    Download a free trial version of IBM Rational Developer for System z, software that can help you deliver core development capabilities; the power of Java Platform, Enterprise Edition (Java EE); and rapid application development support to diverse enterprise application development teams. With comprehensive development tools to help create, deploy and maintain traditional enterprise and composite applications, Rational Developer for System z enables developers with different technical backgrounds to easily participate in important technology projects.
    FREE! Go There Now!


    NEW! Evaluate IBM Rational Software Analyzer V7.0

    Download a free trial version of IBM Rational Software Analyzer Developer Edition V7.0 to identify bug defects earlier in the software development cycle. Rational Software Analyzer is an extensible software development solution that reduces the expense of bug-fixes by enabling static analysis code reviews and bug identification very early in the development cycle.
    FREE! Go There Now!


    NEW! Rational Talks to You:Per Kroll on Rational Method Composer Plug-in customization

    Join this Rational Talks to You teleconference on December 11 at 1:00 pm ET to get tips on building your own plugins with Rational Method Composer. Get your questions answered!
    FREE! Go There Now!


    NEW! Rational Talks to You: Grady Booch on Architecture

    Join this Rational Talks to You teleconference on November 29 at 1:00 pm ET to participate in an interactive discusssion with Grady Booch around architecture and reuse. Get your questions answered!
    FREE! Go There Now!


    NEW! Section 508 of the U.S. Rehabilitation Act: Web accessibility compliance

    Because access to government information continues to be an area of concern for many U.S. citizens with disabilities, the U.S. government enacted Section 508 of the Rehabilitation Act in 2001 to ensure that government agencies create accessible Web content, enabling all citizens to access the information they need. A fully accessible Web site makes Web content accessible to all individuals, including those with disabilities, who may be accessing Web content via a variety of user agents. Common user agents include standard Web browsers, text-only browsers, assistive devices and mobile devices such as cell phones or personal digital assistants (PDAs).
    FREE! Go There Now!


    NEW! Webcast: Application security testing and Web compliance

    Join the IBM Watchfire team for an informative discussion on techniques and best practices to proactively manage Web application security and how to effectively build application security testing into the software development lifecycle (SDLC). In this Software Delivery Platform webcast you will learn: How to better understand potential web application security vulnerabilities, best practices and how to effectively integrate application security testing into the software development lifecycle, the importance of detecting and removing software vulnerabilities during application development.
    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-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek