Thumbnail al volo con php

Script veloce, veloce che ci permette di ridimensionare le img inseriti nel nostro sito con misura impostata nell'url dell'img:
########inizio codice###########
if (!isset($image)){ // if not generate an error image
$img = ImageCreate(100, 100);
$red = ImageColorAllocate($img, 255, 0, 0);
$yellow = ImageColorAllocate($img, 255, 255, 0);
ImageString($img, 5, 20, 20, "Bad", $yellow);
ImageString($img, 5, 20, 40, "size", $yellow);
ImageString($img, 5, 20, 60, "given!", $yellow);
ImagePNG($img);
ImageDestroy($img);
exit();
}

// attempt to load the big image
if (!$bigimage = @ImageCreateFromJPEG($image)) { // if loading fails
$img = ImageCreate(80, 80); // generate an error
$red = ImageColorAllocate($img, 255, 0, 0); // image
$yellow = ImageColorAllocate($img, 255, 255, 0);
ImageString($img, 5, 20, 20, "Image", $yellow);
ImageString($img, 5, 20, 40, "not", $yellow);
ImageString($img, 5, 20, 60, "found!", $yellow);
ImagePNG($img);
ImageDestroy($img);
exit();
}

// all seems to be OK so start the processing
// create the new image using the tnsize parameter
$tnimage = imagecreatetruecolor($tnsize, $tnsize);
// allocate the background colour for the thumbnail
$darkblue = imagecolorallocatealpha($tnimage, 0, 0, 127);
// set the background as transparent
imagecopyresampled($tnimage,$darkblue);
imagefilledrectangle($tnimage, 0, 0, $destW, $destH, $darkblue);
// get the parameters of the big image
$sz = GetImageSize($image);
// load our internal variables
$x = $sz[0]; // big image width
$y = $sz[1]; // big image height
// find the larger dimension
if ($x>$y) { // if it is the width then
$dx = 0; // the left side of the new image
$w = $tnsize; // the width of the new image
$h = ($y / $x) * $tnsize; // the height of the new image
$dy = 0; // the top of the new image
}else{ // if the height is larger then
$dy = 0; // the top of the new image
$h = $tnsize; // the height of the new image
$w = ($x / $y) * $tnsize; // the width of the new image
$dx = 0; // the left edgeof the new image
}
if ($w>$h) {
$tnimage = imagecreatetruecolor($w, $h);
}else{
$tnimage = imagecreatetruecolor($w, $h);
}
// copy the resized version into the thumbnal image
imageCopyResampled($tnimage, $bigimage, $dx, $dy, 0, 0, $w, $h, $x, $y);
// generate the PNG image
ImagePNG($tnimage);
// release the memory used by the thumbnail image
ImageDestroy($tnimage);
// release the memory used by the original big image
ImageDestroy($bigimage);
// all done!
####fine cod#########################

l'immagine la richiamiamo così:
img src="tnp.php?big.jpg&tnsize=150" dove tnp.php è il file dove metteremo il codice sopra riportato sopra. e la var tnsize e la misura max che vogliamo dare alla nostra img.
Utilissimo

Nessun commento:

Posta un commento