Sunteți pe pagina 1din 3

Creating thumbnail in php code

Just create two folder images and another inside images/thumbs and keep original
images in images

<?php
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )
{
// open the directory
$dir = opendir( $pathToImages );

// loop through it, looking for any/all JPG files:


while (false !== ($fname = readdir( $dir ))) {
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( strtolower($info['extension']) == 'jpg' )
{
echo "Creating thumbnail for {$fname} <br />";

// load image and get image size


$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );

// calculate thumbnail size


$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );

// create a new temporary image


$tmp_img = imagecreatetruecolor( $new_width, $new_height );

// copy and resize old image into new image


imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width,
$height );

// save thumbnail into a file


imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
}
}
// close the directory
closedir( $dir );
}
// call createThumb function and pass to it as parameters the path
// to the directory that contains images, the path to the directory
// in which thumbnails will be placed and the thumbnail's width.
// We are assuming that the path will be a relative path working
// both in the filesystem, and through the web for links
createThumbs("images/","images/thumbs/",100);
?>

Extra Practice

<?
function createThumbnail($imageDirectory, $imageName, $thumbDirectory,
$thumbWidth)
{
$srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");
$origWidth = imagesx($srcImg);
$origHeight = imagesy($srcImg);

$ratio = $origWidth / $thumbWidth;


$thumbHeight = $origHeight * $ratio;

$thumbImg = imagecreate($thumbWidth, $thumbHeight);


imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight,
imagesx($thumbImg), imagesy($thumbImg));

imagejpeg($thumbImg, "$thumbDirectory/$imageName");
}

createThumbnail("img", "theFileName.jpg", "img/thumbs", 100);


?>

Printing thumbnail images

<?php

$path = "images/thumbs/";
$dir_handle = @opendir($path) or die("Unable to open folder");

while (false !== ($file = readdir($dir_handle))) {


if($file == "index.php")
continue;
if($file == ".")
continue;
if($file == "..")
continue;

print('<img src="images/thumbs/'.$file.'" alt="'.$file.'"><br>');// "<img src='$file'


alt='$file'><br />";

}
closedir($dir_handle);

?>

S-ar putea să vă placă și