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;
echo('<img src="doImage.php?blob_id=1&resize=225,225" />');
echo('<img src="doImage.php?blob_id=1" />');
<?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;
}
?>
<?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;
?>
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.
You now have a working example of how to display and resize images from your MySQL database onto your website!
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.
Comments (0)