PHP script to create thumbnails for images
The task:
Write a PHP script to get images from database (database table “PHOTOS”), resize them and output them in the browser.
Here’s my quick solution(not optimized):
thumb.php
[sourcecode language=”php”]
<?php
require_once(‘dbconfig.php’); // file that stores our database connection variables
require_once(‘functions.php’); // resize script
try {
if (!isset($_GET[‘id’])) {
throw new Exception(‘ID not specified’);
}
$id = (int) $_GET[‘id’];
if ($id <= 0) {
throw new Exception(‘Invalid ID specified’);
}
$query = sprintf(‘select * from PHOTOS where id = %d’, $id);
$result = mysql_query($query, $db);
if (mysql_num_rows($result) == 0) {
throw new Exception(‘Image with specified ID not found’);
}
$image = mysql_fetch_array($result);
}
catch (Exception $ex) {
header(‘HTTP/1.0 404 Not Found’);
exit;
}
header(‘Content-type: ‘ . $image[‘mime_type’]);
$width = 140;
$height = 140;
$folder = ‘scripts’;
$conflen=strlen($folder);
$B=substr(__FILE__,0,strrpos(__FILE__,’/’));
$A=substr($_SERVER[‘DOCUMENT_ROOT’], strrpos($_SERVER[‘DOCUMENT_ROOT’], $_SERVER[‘PHP_SELF’]));
$C=substr($B,strlen($A));
$posconf=strlen($C)-$conflen-1;
$D=substr($C,1,$posconf);
if($_SERVER[‘SERVER_PORT’] == "8888"){
$host=’http://’.$_SERVER[‘SERVER_NAME’].’:8888/’.$D;}
else {
$host=’http://’.$_SERVER[‘SERVER_NAME’].$_SERVER[‘PHP_SELF’];}
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($host.$folder."/view.php?id=$id");
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromstring($image[‘photodata’]);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagejpeg($image_p, null, 100);
mysql_free_result($result);
?>
[/sourcecode]
functions.php
[sourcecode language=”php”]
<?php
function make_thumb($src,$desired_width)
{
/* read the source image */
$source_image = imagecreatefromstring($src);
$width = imagesx($source_image);
$height = imagesy($source_image);
/* find the "desired height" of this thumbnail, relative to the desired width */
$desired_height = floor($height*($desired_width/$width));
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width,$desired_height);
/* copy source image at a resized size */
imagecopyresized($virtual_image,$source_image,0,0,0,0,$desired_width,$desired_height,$width,$height);
//header(‘Content-Type: image/jpeg’);
imagejpeg($virtual_image, NULL, 100);
}
?>
[/sourcecode]