Google
 
Main Page
 The gatekeeper of reality is
 quantified imagination.

Stay notified when site changes by adding your email address:

Your Email:

Bookmark and Share
Email Notification
Project "Image to mySQL"
Purpose
The purpose of this tutorial is to show how to accept an image upload with PHP, resize that image into a series of images, store those resized images in a mySQL database table as well as displaying images stored in a mySQL database table.

Download full source of the tutorial here

Introduction
In the PHP code you'll notice a series of calls to functions like "imagecreatetruecolor()", "imagejpeg()", "imagepng()" and "imagedestroy()" which rely on the GD library. If your particular instance of PHP does not recognize those functions, you may need to get the GD library installed as documented here.

The actual image upload and display process involves three webpages / PHP scripts:
  1. A simple form that allows a user to select an image on their device to upload
  2. A webpage to process the uploaded image by resizing it into a series of images and saving those to a mySQL database table
  3. A webpage to retrieve an image from a mySQL database table
In this particular tutorial, as mentioned, an uploaded image is resized into a series of separate images and stored in a database. The reason for resizing the original image into a series of images one time is to reduce processing overhead of the image each time it is requested in the future. That is, instead of getting an image from the database and resizing it each time it is requested, we can just return the needed image from the database (which is already the size needed).

The last thing to mention is, because resized images are being stored in the database, "ob_get_contents()" is being used. This function captures the output of "imagejpeg()" and "imagepng()" so we can easily import that stream (normally intended to either go to a web browser or a file on the filesystem) into the database.

Let's get started!

Accept Image Upload From Form
You can add your own picture (JPG, PNG) by selecting the image below.<br /><br />
<form method="post" action="imgUploadHandle.php" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="userSbtBtn" value="Upload Image" />
</form>


Resize / Save Image to mySQL Database Table
$imgStoreLocation = "/home/yoursite/public_html/tmp/"; /* Location on your website where re-sized images are temporarily stored so that their file sizes can be determined */
$imgMaxFileSize = 9765; /* Maximum filesize to accept (10MB): 10,000,000 / 1024 = 9765 */

define("MAX_SIZE", $imgMaxFileSize);
$error_status = 0;
$error_message = "";
$img_mime_type = "";
$img_100_height = 0;
$img_100_size = 0;
$img_300_height = 0;
$img_300_size = 0;
$img_1024_height = 0;
$img_1024_size = 0;

/*
FUNCTION TO STORE RESIZED IMAGES INTO MYSQL DATABASE TABLE
NOTE: The example database table could be represented as --
CREATE TABLE imgUploadTbl (
imgID INT NOT NULL AUTO_INCREMENT
, imgCreatedOn DATETIME NOT NULL
, imgUpdatedOn TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
, imgDimension VARCHAR(100) NOT NULL
, imgMime VARCHAR(255) NOT NULL
, imgSize INT NOT NULL
, imgData LONGBLOB NOT NULL
, PRIMARY KEY(imgID))
*/
function userImgUploadAccept($imgDimension, $imgMime, $imgSize, $imgData) {
$status = "success";
$mySQLLogin = "mySQL user name with permissions to select and insert data";
$mySQLPassword = "mySQL user password with permissions to select and insert data";
$mySQLDatabaseName = "testingDB";
$mySQLDatabaseTableName = "imgUploadTbl";

// Setup connection
$connDB = new PDO("mysql:host=localhost;dbname=$mySQLDatabaseName", $mySQLLogin, $mySQLPassword);
$connDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Add the resized image
try {
// Query
$statement = $connDB->prepare("INSERT INTO '$mySQLDatabaseTableName' (imgCreatedOn, imgDimension, imgMime, imgSize, imgData) values (NOW(), :imgDimension, :imgMime, :imgSize, :imgData)");
// Assign and execute query
$statement->bindParam(':imgDimension', $imgDimension);
$statement->bindParam(':imgMime', $imgMime);
$statement->bindParam(':imgSize', $imgSize);
$statement->bindParam(':imgData', $imgData);
$statement->execute();
}
catch(PDOException $e) { $status = $e->getMessage(); }

//Close the connection
$connDB = null;
return $status;
}

/*
ACCEPT FILE UPLOAD
*/
$image = $_FILES["image"]["name"];
$uploadedfile = $_FILES['image']['tmp_name'];
if ($image) {
$filename = stripslashes($_FILES['image']['name']);

/* Ensure the file is JPG/PNG */
if (($_FILES['image']['type'] != "image/jpg") && ($_FILES['image']['type'] != "image/jpeg") && ($_FILES['image']['type'] != "image/png")) { $error_status = 2; $error_message = "File uploaded was not a JPG or PNG file."; }
else {
/* Ensure the file is less than 10MB */
$size = filesize($_FILES['image']['tmp_name']);
if ($size > (MAX_SIZE * 1024)) { $error_status = 3; $error_message = "File uploaded needs to be less than 10MB."; }
else {
$extension = "jpg";
if(($_FILES['image']['type'] == "image/jpg") || ($_FILES['image']['type'] == "image/jpeg")) { $uploadedfile = $_FILES['image']['tmp_name']; $src = imagecreatefromjpeg($uploadedfile); }
else if (($_FILES['image']['type'] == "image/png")) { $extension = "png"; $uploadedfile = $_FILES['image']['tmp_name']; $src = imagecreatefrompng($uploadedfile); }
$img_mime_type = $_FILES['image']['type'];

/* Get original dimensions of the image */
list($width, $height) = getimagesize($uploadedfile);

/* Resize the original image to 100, 300, 1020 */
/* Resize 1 */
$img_100_height = ($height / $width) * 100;
$img_100_tmp = imagecreatetruecolor(100, $img_100_height);
imagecopyresampled($img_100_tmp, $src, 0, 0, 0, 0, 100, $img_100_height, $width, $height);
ob_start(); if ($extension == "jpg") { imagejpeg($img_100_tmp); } else { imagepng($img_100_tmp); } $img_100_tmpStream = ob_get_contents(); ob_end_clean();

/* Resize 2 */
$img_300_height = ($height / $width) * 300;
$img_300_tmp = imagecreatetruecolor(300, $img_300_height);
imagecopyresampled($img_300_tmp, $src, 0, 0, 0, 0, 300, $img_300_height, $width, $height);
ob_start(); if ($extension == "jpg") { imagejpeg($img_300_tmp); } else { imagepng($img_300_tmp); } $img_300_tmpStream = ob_get_contents(); ob_end_clean();

/* Resize 3 */
/* Note: Resizing does not work if on a byte-boundary such as 1024; so use a somewhat smaller number that is not on a byte-boundary */
$img_1024_height = ($height / $width) * 1020;
$img_1024_tmp = imagecreatetruecolor(1020, $img_1024_height);
imagecopyresampled($img_1024_tmp, $src, 0, 0, 0, 0, 1020, $img_1024_height, $width, $height);
ob_start(); if ($extension == "jpg") { imagejpeg($img_1024_tmp); } else { imagepng($img_1024_tmp); } $img_1024_tmpStream = ob_get_contents(); ob_end_clean();

/* Get file sizes of the resized images by temporarily dumping them to the filesystem */
$today = date("YmdHis"); $physicalPath = $imgStoreLocation . $today;

/* Temporarily save images to the filesystem */
if ($extension == "jpg") {
imagejpeg($img_100_tmp, $physicalPath . "_100." . $extension);
imagejpeg($img_300_tmp, $physicalPath . "_300." . $extension);
imagejpeg($img_1024_tmp, $physicalPath . "_1024." . $extension);
}
else {
imagepng($img_100_tmp, $physicalPath . "_100." . $extension);
imagepng($img_300_tmp, $physicalPath . "_300." . $extension);
imagepng($img_1024_tmp, $physicalPath . "_1024." . $extension);
}

/* Get image sizes in bytes */
$img_100_size = filesize($physicalPath . "_100." . $extension);
$img_300_size = filesize($physicalPath . "_300." . $extension);
$img_1024_size = filesize($physicalPath . "_1024." . $extension);

/* Remove files from filesystem */
unlink($physicalPath . "_100." . $extension);
unlink($physicalPath . "_300." . $extension);
unlink($physicalPath . "_1024." . $extension);

/* Save resized images to database */
$status = userImgUploadAccept(100, $img_mime_type, $img_100_size, $img_100_tmpStream);
if ($status == "success") { $status = userImgUploadAccept(300, $img_mime_type, $img_300_size, $img_300_tmpStream); }
if ($status == "success") { $status = userImgUploadAccept(1024, $img_mime_type, $img_1024_size, $img_1024_tmpStream); }
if ($status != "success") {
$error_status = 4;
$error_message = "There was a problem adding resized images to the database.";
}
/* Free up memory */
imagedestroy($src);
imagedestroy($img_100_tmp);
imagedestroy($img_300_tmp);
imagedestroy($img_1024_tmp);
}
}
}
else { $error_status = 1; $error_message = "There was a problem with the file being uploaded."; }

/*
PAGE OUTPUT
*/
print "<html><head>\n";
print "<title>Image Upload Status</title>\n";
print "</head><body>\n";
print $error_status . " " . $error_message;
print "</body>\n";
print "</html>\n";


Display Image from mySQL Database Table
global $imgMime;
global $imgSize;
global $imgData;
$error_status = 0;
$requestedID = 0;

/*
DATABASE TABLE STRUCTURE (for this example):
CREATE TABLE imgUploadTbl (
imgID INT NOT NULL AUTO_INCREMENT
, imgCreatedOn DATETIME NOT NULL
, imgUpdatedOn TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
, imgDimension VARCHAR(100) NOT NULL
, imgMime VARCHAR(255) NOT NULL
, imgSize INT NOT NULL
, imgData LONGBLOB NOT NULL
, PRIMARY KEY(imgID))
*/
function imgRetrieve($id) {
global $imgMime;
global $imgSize;
global $imgData;
$status = "success";
$mySQLLogin = "mySQL user name with permissions to select and insert data";
$mySQLPassword = "mySQL user password with permissions to select and insert data";
$mySQLDatabaseName = "testingDB";
$mySQLDatabaseTableName = "imgUploadTbl";

// Setup connection
$connDB = new PDO("mysql:host=localhost;dbname=$mySQLDatabaseName", $mySQLLogin, $mySQLPassword);
$connDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
// Query
$statement = $connDB->prepare("SELECT imgMime, imgSize, imgData FROM '$mySQLDatabaseTableName' WHERE imgID = :imgID");
// Assign and execute query
$statement->bindParam(':imgID', $id, PDO::PARAM_INT);
$statement->setFetchMode(PDO::FETCH_ASSOC);
$statement->execute();
// Get data
while($row = $statement->fetch()) {
$imgMime = $row['imgMime'];
$imgSize = $row['imgSize'];
$imgData = $row['imgData'];
}
}
catch(PDOException $e) { $status = $e->getMessage(); }

//Close the connection
$connDB = null;
return $status;
}

/*
PROCESS THE REQUEST FOR THE IMAGE
*/
try { $requestedID = (int)$_GET[id]; }
catch (Exception $e) { $error_status = 1; }
if ($error_status == 0) {
$status = imgRetrieve($requestedID);
if ($status == "success") {
if ((int)$imgSize > 0) {
header('Content-type: ' . $imgMime);
header('Content-length: ' . $imgSize);
echo $imgData;
}
else { header('HTTP/1.0 404 Not Found'); }
}
else { header('HTTP/1.0 500 Internal Server Error'); }
}
else { header('HTTP/1.0 400 Bad Request'); }
About Joe