Resize Image And Create Thumbnail With Aspect Ratio

Here’s a little script how to create thumbnail with PHP and GD library and still keeping aspect ratio. You only need to specify new image’s maximum width and height.

By default, it will create a maximum 110×110 pixel, both width or height, depend on which is longer.

< ?php /* Function to create thumbnail from an image Example: makeThumb('img/image.jpg','img/thumbnail/','gambar_kecil.jpg','',150,150); */ function makeThumb($file,$thumb_dir,$new_name="",$resize="10",$new_width="110",$new_height="110"){ // get file info $size = getimagesize($file); $width = $size[0]; $height = $size[1]; if(!$new_name){ $filename = basename($file); } else{ $filename = $new_name; } // new size if($resize){ $new_w = ($width*($resize/100)); $new_h = ($height*($resize/100)); } else{ // tentuin new width and height $new_w = $new_width; $new_h = $new_height; if($width>=$height){
elseif($width< =$height){ $stat="ver"; } if($stat=="hor"){ $new_h=$height*$new_w/$width; } elseif($stat=="ver"){ $new_w=$width*$new_h/$height; } } // ayo menggambar $src_img = imagecreatefromjpeg($file); $dst_img = imagecreatetruecolor($new_w,$new_h); imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $new_w, $new_h, $width, $height); imagejpeg($dst_img,$thumb_dir.$filename,100); // bersihin sampah memori imagedestroy($src_img); imagedestroy($dst_img); } ?>

Don’t forget to create [b]thumbnail[/b] directory first. Have phun!



Add yours

  1. Hi,

    use this script to resize image to different aspect ratio. for example, resizing 1024×800 image to 120×120.

Leave a Reply