Resizing and Displaying Images In PHP from a MySQL Database

AID: 4194
  • Status: Published

2480 points

  • Bypatsmitty
  • TypeTutorial
  • Posted on2010-12-04 at 16:05:25
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:
 
fb.jpeg
  • 192 KB
  • Screen-Shot of www.facebook.com
Screen-Shot of www.facebook.com

The 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;

                                    
1:
2:
3:
4:
5:
6:
7:
8:

Select allOpen 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" />');

                                    
1:

Select allOpen 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" />');

                                    
1:

Select allOpen 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;
}

?>

                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:

Select allOpen 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;
        ?>

                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:

Select allOpen 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:
db.png
  • 9 KB
  • Screen-Shot of My Database Contents
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:
scr1.png
  • 262 KB
  • Screen_Shot of My Example
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!
    Asked On
    2010-12-04 at 16:05:25ID4194
    Tags

    PHP

    ,

    MySQL

    ,

    blob

    ,

    database

    ,

    jpg

    ,

    jpeg

    ,

    resize

    ,

    re-size

    ,

    image

    ,

    images

    Topic

    PHP Scripting Language

    Views
    1440

    Comments

    Add your Comment

    Please Sign up or Log in to comment on this article.

    Join Experts Exchange Today

    Gain Access to all our Tech Resources

    Get personalized answers

    Ask unlimited questions

    Access Proven Solutions

    Search 3.2 million solutions

    Read In-Depth How-To Guides

    1000+ articles, demos, & tips

    Watch Step by Step Tutorials

    Learn direct from top tech pros

    And Much More!

    Your complete tech resource

    See Plans and Pricing

    30-day free trial. Register in 60 seconds.

    Loading Advertisement...

    Top PHP Experts

    1. Ray_Paseur

      1,354,218

      Genius

      3,734 points yesterday

      Profile
      Rank: Savant
    2. DaveBaldwin

      284,951

      Guru

      4,300 points yesterday

      Profile
      Rank: Genius
    3. StingRaY

      144,754

      Master

      4,000 points yesterday

      Profile
      Rank: Wizard
    4. jason1178

      143,172

      Master

      1,000 points yesterday

      Profile
      Rank: Genius
    5. bportlock

      123,643

      Master

      1,600 points yesterday

      Profile
      Rank: Genius
    6. ChrisStanyon

      111,336

      Master

      0 points yesterday

      Profile
      Rank: Sage
    7. Roads_Roads

      106,350

      Master

      0 points yesterday

      Profile
      Rank: Genius
    8. maeltar

      95,247

      Master

      0 points yesterday

      Profile
      Rank: Guru
    9. gr8gonzo

      95,168

      Master

      0 points yesterday

      Profile
      Rank: Sage
    10. smadeira

      82,088

      Master

      0 points yesterday

      Profile
      Rank: Wizard
    11. Slick812

      77,062

      Master

      0 points yesterday

      Profile
      Rank: Sage
    12. johanntagle

      74,700

      Master

      2,000 points yesterday

      Profile
      Rank: Sage
    13. logudotcom

      67,088

      Master

      0 points yesterday

      Profile
      Rank: Genius
    14. COBOLdinosaur

      65,841

      Master

      0 points yesterday

      Profile
      Rank: Genius
    15. leakim971

      63,819

      Master

      0 points yesterday

      Profile
      Rank: Genius
    16. un1x86

      56,406

      Master

      0 points yesterday

      Profile
      Rank: Master
    17. Derokorian

      46,763

      10 points yesterday

      Profile
      Rank: Guru
    18. marqusG

      44,475

      10 points yesterday

      Profile
      Rank: Sage
    19. DrDamnit

      42,892

      0 points yesterday

      Profile
      Rank: Genius
    20. ahoffmann

      40,068

      0 points yesterday

      Profile
      Rank: Genius
    21. designatedinitializer

      37,800

      0 points yesterday

      Profile
      Rank: Master
    22. maestropsm

      37,678

      0 points yesterday

      Profile
      Rank: Guru
    23. TerryAtOpus

      34,800

      0 points yesterday

      Profile
      Rank: Genius
    24. xterm

      32,850

      0 points yesterday

      Profile
      Rank: Sage
    25. kaufmed

      31,808

      0 points yesterday

      Profile
      Rank: Genius

    Hall Of Fame