Thumbnail |
Monday, 5th May 2003 |
How to create a thumbnail and store it in a MySQL database?
That question has kept me busy for weeks, while working on the Dutch real estate web site
huizentoppers.nl.
PHP has powerful functions for image processing.
The web offers good documentation on PHP.
Still, it took me a quest of weeks to gather all necessary coding details.
In order to spare my fellow PHP fans a similar quest, this week's Nut describes all the required PHP source code.
Photo upload, Browser
- Standard HTML support file upload.
- The form parameter specifies that the posted variables may contain multiple parts, the usual variables but possibly also one or more files.
- Some browsers check the file size, if the hidden variable MAX_FILE_SIZE,
precedes the input type=file.
- The input of type file allows users to browse their own PC for a file.
The accept parameter forces some browsers to accept JPG files only.
<HTML>
<form enctype="multipart/form-data" method="post" action="update.php3" name="form1">
<input type="hidden" name="MAX_FILE_SIZE" value="102400">
<input type="file" name="photo" accept="image/jpeg">
<input type="hidden" name="id" value="12345">
<input type=submit value="Send">
</form>
</HTML>
With special thanks for the HTML advises of:
pangaeainc.com, Terry Schmidt.
Photo upload, validation at server
The browser's validation is far from perfect.
So, the PHP script at server side must recheck the input.
- The properties of uploaded files are in the multi dimensional array $_FILES.
- The 1st key is the name of the file from the input type=file tag.
- The 2nd key is the property name, e.g. 'name' for the file name.
- A temporary file on the server contains the uploaded file.
The name of that temporary file is found in $_FILES with 2nd key 'tmp_name'.
- A JPG extension is no 100% guarantee that the uploaded file is a true JPG.
The function imagecreatefromstring() tries to create an image out of the file contents.
If that succeeds the file is a true JPG.
<?php
$sPhotoFileName = $_FILES['photo']['name']; // get client side file name
if ($sPhotoFileName) // file uploaded
{ $aFileNameParts = explode(".", $sPhotoFileName);
$sFileExtension = end($aFileNameParts); // part behind last dot
if ($sFileExtension != "jpg"
&& $sFileExtension != "JPEG"
&& $sFileExtension != "JPG")
{ die ("Choose a JPG for the photo");
}
$nPhotoSize = $_FILES['photo']['size']; // size of uploaded file
if ($nPhotoSize == 0)
{ die ("Sorry. The upload of $sPhotoFileName has failed.
Search a photo smaller than 100K, using the button.");
}
if ($nPhotoSize > 102400)
{ die ("Sorry.
The file $sPhotoFileName is larger than 100K.
Advice: reduce the photo using a drawing tool.");
}
// read photo
$sTempFileName = $_FILES['photo']['tmp_name']; // temporary file at server side
$oTempFile = fopen($sTempFileName, "r");
$sBinaryPhoto = fread($oTempFile, fileSize($sTempFileName));
// Try to read image
$nOldErrorReporting = error_reporting(E_ALL & ~(E_WARNING)); // ingore warnings
$oSourceImage = imagecreatefromstring($sBinaryPhoto); // try to create image
error_reporting($nOldErrorReporting);
if (!$oSourceImage) // error, image is not a valid jpg
{ die ("Sorry.
It was not possible to read photo $sPhotoFileName.
Choose another photo in JPG format.");
}
}
?>
Source:
php.net/....
Create thumbnail
- Cropping and scaling a photo is surprisingly easy with PHP.
- Unfortunately the functions
imagecreatetruecolor()
and
imagecopyresampled()
exist only since PHP 4.0.6 using GD 2.0.1.
Older PHP version supports the functions
imagecreate()
and
imagecopyresized(),
which are good enough to do the job.
- It is possible to generate a thumbnail on the fly, in RAM memory, using
ob_start()
and
ob_end_clean().
That saves unnecessary fumbling around with temporary files.
- Pictures require a lot of disk size.
The
imageJPEG()
reduces the image quality down to 75% by default.
This saves space in the database and speeds up the thumbnail download to the browser.
<?php
$nWidth = imagesx($oSourceImage); // get original source image width
$nHeight = imagesy($oSourceImage); // and height
// create small thumbnail
$nDestinationWidth = 80;
$nDestinationHeight = 60;
//$oDestinationImage = imagecreatetruecolor($nDestinationWidth, $nDestinationHeight);
$oDestinationImage = imagecreate($nDestinationWidth, $nDestinationHeight);
/*$oResult = imagecopyresampled(
$oDestinationImage, $oSourceImage,
0, 0, 0, 0,
$nDestinationWidth, $nDestinationHeight,
$nWidth, $nHeight); // resize the image
*/
imagecopyresized(
$oDestinationImage, $oSourceImage,
0, 0, 0, 0,
$nDestinationWidth, $nDestinationHeight,
$nWidth, $nHeight); // resize the image
ob_start(); // Start capturing stdout.
imageJPEG($oDestinationImage); // As though output to browser.
$sBinaryThumbnail = ob_get_contents(); // the raw jpeg image data.
ob_end_clean(); // Dump the stdout so it does not screw other output.
?>
BLOB in MySQL database
MySQL offers an easy feature to store photo's, drawings and documents.
MySQL supports BLOBS,
binary large objects
in several sizes
mysql.com/....
A standard size BLOB is large enough for photos.
Store Thumbnail in database
- The binary contents of a photo heads straight for the BLOB, as if it is one long string.
- Use the function
addslashes
to preserve special ASCII values that match quotes.
<?php
$sBinaryThumbnail = addslashes($sBinaryThumbnail);
$oDatabase = mysql_connect("localhost", "your_database_user_id", "your_database_password");
mysql_select_db("your_database_name", $oDatabase);
$sQuery = "UPDATE your_table
SET thumbnail = '$sBinaryThumbnail'
WHERE id = '$nId'";
mysql_query($sQuery, $oDatabase);
?>
Source, article on BLOBs:
zdnetindia.com/...
Show Thumbnail
![]() |
Thumbnail: , |
- Create an image tag with the URL of a special PHP thumbnail script as SRC parameter.
- Specify the width and height in the IMG tag so the browser can render the page,
before the thumbnail has been loaded.
<HTML>
<img src="thumbnail.php?id=12345" width=80 height=60>
</HTML>
- The PHP thumbnail script pretends to be a JPG file, sends an image to the browser.
<?php
header("Content-type: image/jpeg"); // act as a jpg file to browser
$oDatabase = mysql_connect("localhost", "your_database_user_id", "your_database_password");
mysql_select_db("your_database_name", $oDatabase);
$sQuery = "SELECT thumbnail
FROM your_table
WHERE id = $nId";
$oResult = mysql_query($sQuery, $oDatabase);
$oRow = mysql_fetch_array($oResult);
$sJpg = $oRow["thumbnail"];
echo $sJpg;
?>
Source, the same story on BLOBs:
zdnetindia.com/...
Special thanks to Russell Graves for debugging.
Till
next nut,
Nut