pertama kita buat dulu file html nya
<form method="post" action="<? $_SERVER['PHP_SELF'];?>" enctype="multipart/form-data">
<table border="0">
<tr>
<td>Image</td><td><input type="file" name="image" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="upload" /></td>
</tr>
</table>
</form>
lalu kita buat function nya dalam satu file php. Dalam function nya terdapat parameter - parameter diantaranya kita bisa menentukan ukuran pixel untuk width & height nya. <?
function cropImage($nw, $nh, $source, $dest)
{
list($w, $h, $stype) = getimagesize($source);
if ($stype == NULL) {
return false;
}
switch($stype) { // format gambar
case IMAGETYPE_GIF:
$simg = imagecreatefromgif($source);
break;
case IMAGETYPE_JPEG:
$simg = imagecreatefromjpeg($source);
break;
case IMAGETYPE_PNG:
$simg = imagecreatefrompng($source);
break;
}//switch
$dimg = imagecreatetruecolor($nw, $nh); // menciptakan image baru
$wm = $w/$nw;
$hm = $h/$nh;
$h_height = $nh/2;
$w_height = $nw/2;
if($w> $h)
{
$adjusted_width = $w / $hm;
$half_width = $adjusted_width / 2;
$int_width = $half_width - $w_height;
imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
}
elseif(($w <$h) || ($w == $h))
{
$adjusted_height = $h / $wm;
$half_height = $adjusted_height/ 2;
$int_height = $half_height - $h_height;
imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);
}
else
{
imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
}
imagejpeg($dimg,$dest,100);
}
?>
kemudian untuk proses upload nya listing nya seperti berikut <?
require_once('resize_image.php');
$file=$_FILES['image']['name'];
if($file!="")
{
$path="image/".$file;
$dest="image/thumb_".$file;
copy($_FILES['image']['tmp_name'],$path);
cropImage(100, 100, $path, $dest);
$size_thumb = getimagesize($dest); // ukuran gambar
$w_thumb = $size_thumb[0];
$h_thumb = $size_thumb[1];
$size=getimagesize($path);
$w=$size[0];
$h=$size[1];
}
?>
Untuk menampilkan image nya dalam page <img src="image/thumb_<? echo $file;?>" width="100" height="100"/>
<p><? echo "filename : thumb_". $file;?></p>
<p><? echo "width :".$w_thumb." px";?></p>
<p><? echo "height :".$h_thumb." px";?></p>
<br />
<br />
<img src="image/<? echo $file;?>" />
<p><? echo "filename : ". $file;?></p>
<p><? echo "width :".$w." px";?></p>
<p><? echo "height :".$h." px";?></p>
variabel - variabel sudah di set di dalam proses upload file. Gimana sederhana kan, sekarang kita bisa membuat image gallery yang disertai dengan image thumbnail dan pastinya itu keren. source code nya bisa di download disini

Tidak ada komentar:
Posting Komentar