Creare Thumbs con PHP

Maggio 15, 2008

In questo breve post vedremo come creare delle miniature di immagini (thumbnails) durante l’upload.

Codice PHP:

<?php
define (”MAX_SIZE”,”100″);
define (”WIDTH”,”150″);
define (”HEIGHT”,”100″);

function make_thumb($img_name,$filename,$new_w,$new_h)
{
//ricavo estensione immagine.
$ext=getExtension($img_name);
if(!strcmp(”jpg”,$ext) || !strcmp(”jpeg”,$ext))
$src_img=imagecreatefromjpeg($img_name);

if(!strcmp(”png”,$ext))
$src_img=imagecreatefrompng($img_name);
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);

$ratio1=$old_x/$new_w;
$ratio2=$old_y/$new_h;
if($ratio1>$ratio2)    {
$thumb_w=$new_w;
$thumb_h=$old_y/$ratio1;
}
else    {
$thumb_h=$new_h;
$thumb_w=$old_x/$ratio2;
}

// creo una nuova immagine con le nuove dimensioni
$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(!strcmp(”png”,$ext))
imagepng($dst_img,$filename);
else

imagejpeg($dst_img,$filename);
imagedestroy($dst_img);
imagedestroy($src_img);
}

function getExtension($str) {
$i = strrpos($str,”.”);
if (!$i) { return “”; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}

$errors=0;

if(isset($_POST['Submit']))
{
$image=$_FILES['image']['name'];

if ($image)
{

$filename = stripslashes($_FILES['image']['name']);

$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != “jpg”)  && ($extension != “jpeg”) && ($extension != “png”))
{
echo ‘<h1>Estensione sconosciuta!</h1>’;
$errors=1;
}
else
{
$size=getimagesize($_FILES['image']['tmp_name']);
$sizekb=filesize($_FILES['image']['tmp_name']);

if ($sizekb > MAX_SIZE*1024)
{
echo ‘<h1>Hai superato il limite massimo per upload!</h1>’;
$errors=1;
}

$image_name=time().’.’.$extension;
$newname=”nome_cartella/”.$image_name;
$copied = copy($_FILES['image']['tmp_name'], $newname);

if (!$copied)
{
echo ‘<h1>Copia non avvenuta!</h1>’;
$errors=1;
}
else
{
$thumb_name=’nome_cartella/cartella_thumbs/thumb_’.$image_name;
$thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT);
}}    }}

if(isset($_POST['Submit']) && !$errors)
{
echo “<h1>il Thumbnail è stato creato con successo!</h1>”;
echo ‘<img src=”‘.$thumb_name.’”>’;
}

?>

Entry Filed under: Scripts. Tag: .

Leave a Comment

You must be logged in to post a comment.

Trackback this post  |  Subscribe to the comments via RSS Feed


Categorie

Articoli Recenti

Tag