สามารถใช้ฟังก์นี้ในการสร้างรูปภาพ thumbnail จากรูปภาพขนาดใหญ่
โดยสามารถกำหนดความกว้าง ความสูงใหม่ ตามต้องการได้
<?php
function createthumb($name,$filename,$new_w,$new_h){
$system=explode('.',$name);
if(preg_match('/jpg|jpeg/',$system[1])){
$src_img=imagecreatefromjpeg($name);
}
if(preg_match('/png/',$system[1])){
$src_img=imagecreatefrompng($name);
}
$old_x=imagesx($src_img);
$old_y=imagesy($src_img);
$thumb_w=($old_x*$new_h)/$old_y;
$thumb_h=$new_h;
$co_x=floor(($new_w-$thumb_w)/2);
$co_y=0;
$dst_img=imagecreatetruecolor($new_w,$thumb_h);
$white=imagecolorallocate($dst_img,255,255,255);
imagefill($dst_img,0,0,$white);
imagecopyresized($dst_img,$src_img,$co_x,$co_y,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
if(preg_match("/png/",$system[1])){
imagepng($dst_img,$filename);
}else{
imagejpeg($dst_img,$filename);
}
imagedestroy($dst_img);
imagedestroy($src_img);
}
?>
การใช้งานฟังก์ชันสร้าง thumbnail
<?php
createthumb('mypic3.jpg','thumbmypic1.jpg',300,225); การใช้งาน
// mypic3.jpg ชื่อไฟล์ที่ต้องการเปลี่ยนความกว้างความสูง
// thumbmypic1.jpg ชื่อไฟล์ใหม่ที่ต้องการ
// 300 ความกว้างที่ต้องการ
// 225 ความสูงต้องการ
?>