12-02-2007, 06:59 PM
|
#1 (permalink)
|
|
The Addict
Join Date: Nov 2007
Location: UK
Posts: 315
Thanks: 18
|
Thumbnails from a directory
I have this code i did a awhile ago to create thumbnails out of images from a directory on your web server.
PHP Code:
function createthumb($name,$filename,$new_w,$new_h)
{
$system=explode('.',$name);
if (preg_match('/jpg|jpeg/',$system[1])){
$src_img=imagecreatefromjpeg($name);
}
if (preg_match('/png/',$system[1])){
$src_img=imagecreatefrompng($name);
}
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
if ($old_x > $old_y) {
$thumb_w=$new_w;
$thumb_h=$old_y*($new_h/$old_x);
}
if ($old_x < $old_y) {
$thumb_w=$old_x*($new_w/$old_y);
$thumb_h=$new_h;
}
if ($old_x == $old_y) {
$thumb_w=$new_w;
$thumb_h=$new_h;
}
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
if (preg_match("/png/",$system[1]))
{
imagepng($dst_img,$filename);
} else {
imagejpeg($dst_img,$filename);
}
imagedestroy($dst_img);
imagedestroy($src_img);
}
Create thumbnails and display the results
PHP Code:
$path = "images/";
$img_dir = @opendir($path);
$entriesperline=3; //Number of images on each row of the table
$counter=1;
while ($img_file = readdir($img_dir))
{
createthumb('images/'.$img_file,'thumbs/tn_'.$img_file,100,100);
}
$path = "images/";
$img_dir = @opendir($path);
$entriesperline=5;
$counter=1;
echo "<center><table border='0' width=600 cellspacing=0 cellpadding=5 class=gallery>";
while ($img_file = readdir($img_dir))
{
$filetype = filetype($img_file);
if($img_file!="." && $img_file!=".." && $filetype!="dir")
if($counter%$entriesperline==1)
{
echo "<tr><td><a href=\"images/$img_file\" rel=\"thumbnail\"><img src=thumbs/tn_$img_file border=5></a> </td>";
}
else if($counter%$entriesperline==0)
{
echo "<td><a href=\"images/$img_file\" rel=\"thumbnail\"><img src=thumbs/tn_$img_file border=5></a> </td></tr>";
}
else
{
echo "<td><a href=\"images/$img_file\" rel=\"thumbnail\"><img src=thumbs/tn_$img_file border=5></a> </td>";
}
$counter++;
} //exit loop
$counter--;
if($counter%$entriesperline!=0)
{
echo "</tr>";
}
echo "</table></center>";
The function can easily be set up just to create one thumbnail
PHP Code:
createthumb('link to original image','thumbnail new name and location',width,height);
The new thumbnail should work out the ratio so the image is the same dimensions, but smaller version.
Gets the job done i feel :)
|
|
|