Resizing and Displaying Images In PHP from a MySQL Database

Bruce SmithSoftware Engineer II
Published:
In this tutorial, I will show you how to set up a simple database that holds images and how to re-size and display those images on your website. Here is what the result of this tutorial will look like: http://www.patsmitty.com/ExpertsExchange/BlobArticle.php

The example I am going to use stores screen-shots (.jpeg) of websites. For instance the screen-shot of www.facebook.com looks like this:
 Screen-Shot of www.facebook.comThe database, in my example, will also hold a name and the URL for the screen-shot. The example will neatly show all the images on a page and a clickable link to the URL of the image.

So, here is the to-do list:

1. Create the MySQL Database

Create a MySQL database with a table called "tblBlob" that has the following 4 fields:
blob_id
  This needs to be type Integer and set to AUTO_INCREMENT
blob_name
  Type VARCHAR
blob_url
  Type VARCHAR
blob_binary
  You can set the type to either of the following: BLOB, TINYBLOB, MEDIUMBLOB, OR LONGBLOB. The differences between these are the maximum allowed sizes of of the images you are going to store. A BLOB is a binary field that can store the binary representation of images. For this example I am going to use LONGBLOB.

Here is the MySQL syntax for creating this table:
 
CREATE TABLE `tblBlob` (
                        `blob_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
                        `blob_name` VARCHAR(85) NOT NULL,
                        `blob_url` VARCHAR(185) NOT NULL,
                        `blob_binary` LONGBLOB NOT NULL,
                        PRIMARY KEY (`blob_id`)
                      )
                      ENGINE = InnoDB;
                      

Open in new window


2. Create a PHP script for retrieving and re-sizing the image

Call this script "doImage.php". What's going to happen is, from the main page (which we'll create next) where we will show the images and links, we will set the 'src' inside the image tags to the following:
echo('<img src="doImage.php?blob_id=1&resize=225,225" />');
                      

Open in new window


Notice the two request-variables inside the url: blob_id=1 and resize=225,225. The first one, blob_id=1, retrieves the blob in the database whose blob_id is 1. So if you wanted the 15th blob in the database, you would change that 1 to a 15. (We will dynamically set this variable -- I only went into this for explaining purposes) The second variable, resize=225,225, will size the image to 225 x 225 (h x w). It won't change the blob in the database, it is only for viewing purposes. If you want to just display the original image's size, you can leave this out completely which would give you the following url:
echo('<img src="doImage.php?blob_id=1" />');
                      

Open in new window


The contents of doImage.php need to look like this:
<?php
                      
                      $blob_id = $_REQUEST['blob_id']; //gets the request variable from the url that contains the id of the blob that we want to retrieve from the database
                      mysql_connect('database host-name', 'database user-name', 'password') OR DIE('Unable to connect to database! Please try again later.');
                      mysql_select_db('database-name');
                      $sql = "SELECT blob_name, blob_binary FROM tblBlob WHERE blob_id = '$blob_id'";
                      $result = mysql_query($sql) or exit("QUERY FAILED!");
                      list($blob_name, $blob_url, $blob_binary) = mysql_fetch_array($result);
                      header("Content-type: image/jpeg");
                      header("Content-Disposition: attachment; filename= $blob_name");
                      if ($_REQUEST['resize'] != "" && $_REQUEST['resize'] != null) { //resizes the images if the url contains
                          $dimensions = explode(",", $_REQUEST['resize']);
                          echo resize($blob_binary, $dimensions[0], $dimensions[1]);
                      } else {
                          echo $blob_binary;
                      }
                      
                      function resize($blob_binary, $desired_width, $desired_height) { // simple function for resizing images to specified dimensions from the request variable in the url
                          $im = imagecreatefromstring($blob_binary);
                          $new = imagecreatetruecolor($desired_width, $desired_height) or exit("bad url");
                          $x = imagesx($im);
                          $y = imagesy($im);
                          imagecopyresampled($new, $im, 0, 0, 0, 0, $desired_width, $desired_height, $x, $y) or exit("bad url");
                          imagedestroy($im);
                          imagejpeg($new, null, 85) or exit("bad url");
                          echo $new;
                      }
                      
                      ?>
                      

Open in new window


This script takes the first variable (blob_id) and retrieves that blob from the database. If there is a resize variable, the script will re-size the retrieved image.

This is all we need to do with this script. It is as easy as that! Lastly we need to create the main page that will display all the images with their links.

3. Create Main Page

Create a php webpage and name it whatever you want.
Inside the body of your php page, insert the following code that grabs the ids, names, and urls from your database, then sets the image sources to the respective url I discussed in the last step:
<?php
                              $blob_id = $_REQUEST['blob_id']; //gets the request variable from the url that contains the id of the blob that we want to retrieve from the databse
                              mysql_connect('db host', 'db user-name', 'password') OR DIE('Unable to connect to database! Please try again later.');
                              mysql_select_db('db-name');
                              $sql = "SELECT blob_id, blob_name, blob_url FROM tblBlob";
                              $result = mysql_query($sql) or exit("QUERY FAILED!");
                              if ($result):
                                  while ($row = mysql_fetch_array($result)):
                                      echo('<h2><a href="' . $row['blob_url'] . '">' . $row['blob_name'] . '</a></h2>');
                                      echo('<br />');
                                      echo('<img alt="' . $row['blob_name'] . '" src="doImage.php?blob_id=' . $row['blob_id'] . '&resize=280,215" />');
                                      echo('<br /><hr />');
                                  endwhile;
                              endif;
                              ?>
                      

Open in new window

This will show all the files in your database in a thumbnail-size of (280 x 215) with the Name of the image as a link right above each image.

4. Load Sample Data

Put some sample data in your database. I took screen-shots of 6 different websites and placed them into my database. Here is a screen shot of the contents of my database:
Screen-Shot of My Database Contents

5. Fix Connection Strings and Place Both Files In Same Directory

Go into both files and fix the MySQL connection strings to connect to your database.
Now place both files in the same directory and navigate to the main page that you created. Here is what my example looks like:
Screen_Shot of My Example
You now have a working example of how to display and resize images from your MySQL database onto your website!
1
20,693 Views
Bruce SmithSoftware Engineer II

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.