Studi Kasus : Membuat thumbnail dari gambar dengan PHP GD Library
Kebutuhan : Webserver Packages, already installed. Dan pastikan versi PHP anda mensupport Image GD Library (versi 1-8 keatas)
Ikuti langkah-langkah dibawah.
Step 1 : Persiapkan Folder Kerja
- Buat folder dengan nama tutorphp dalam document root anda
- Siapkan sample JPG image dalam folder ini. Untuk tutorial ini saya menggunakan image dibawah ini (catat : anda bisa menggunakan image apapun, asalkan berekstensi JPG). Jika anda ingin menggunakan image ini, silahkan klik kanan pada image dan pilih save as
- Rename gambar anda dengan nama myPic.jpg (catat : rename ini tidak berarti apapun, hanya untuk memudahkan anda mengikuti tutorial ini π )
Step 2 : Membuat script utama untuk resize image ke dalam thumbnail
- Ketikkan script berikut,
[sourcecode language=”php”]
<?php
$image = ‘myPic.jpg’; //default image, change here if you want to use another image//get the image size and image info
list($width_orig, $height_orig, $image_type) = getimagesize($image);if($image_type !== 2) { // 2 is for JPEG Image
echo ‘Image is not JPEG Image!’;
}
else {
$thumbname = ‘thumbnail_’.$image; //default name for thumbnail version of image// setting the height for the width 75px (75px is default width for the thumbnail). this is for maintain the ratio
$height_tb = (int) ((75 / $width_orig) * $height_orig);//Create a new true color image
$image_p = imagecreatetruecolor(75, $height_tb);//Create a new JPEG image from file or URL
$image = imageCreateFromJpeg($image); ////Copy and resize part of an image with resampling
imagecopyresampled($image_p, $image, 0, 0, 0, 0, 75, $height_tb, $width_orig, $height_orig);//upload image to folder
if(!is_writeable(dirname($thumbname)))
{
echo ‘Unable to Upload image to ‘ . dirname($thumbname);
}
else
{
//output image to browser or file, the parameter is imageJPEG(resource image, name of the image, quality)
imageJpeg($image_p, $thumbname, 100);
}
}
?>
<center><h1>Create Thumbnail Image</h1>
<table border=’1′ cellpadding=’5′ cellspacing=’5′>
<tr align=’center’> <td>Original</td> <td>Thumbnail</td> </tr>
<tr> <td><img src="myPic.jpg" alt="image" /></td> <td><img src="<?php echo $thumbname;?>" alt="thumbnail" /></td></tr>
</table>
<center>
[/sourcecode] - simpan dengan nama imagetb.php, dan simpan dalam folder tutorphp
- Penjelasan : Dapat dilihat di script langsung (script berwarna hijau), Okay
Step 3 : Testing Code
- Pergi ke http://localhost/tutorphp/imagetb.php
- Anda akan melihat image anda tadi (original) beserta versi thumbnailnya π just like the picture below..
- Cek di folder tutor.php. Anda akan menemukan file image thumbnail_myPic.jpg yang merupakan versi thumbnail dari image anda.
π