Converting Image to Thumbnail Image in PHP

Introduction

In this article I explain conversion of a simple image to a thumbnail image in PHP. I will use some PHP code for converting a simple image to a thumbnail image. First of all create two folders in the www directory. One folder for the input image and the other folder for the thumbnail image. I use the $Imagepath variable for storing the image and the next variable, $thumbpath, is for storing the converted thumbnail image.

Example

<?php

$new_width = 150;

$Imagepath = "./Imagefiles";

$Thumbpath = "./Thumbfiles";

$filepath = "./Imagefiles";

$dir = dir($filepath);

while($entry=$dir->read())

 {

    if($entry == "." || $entry == "..")

    {

        continue;

    }

    $fp = @fopen("$filepath/$entry","r");

 $photo_filename = "$entry";

$image_stats = GetImageSize($Imagepath."/".$entry);

$imagewidth = $image_stats[0];

$imageheight = $image_stats[1];

$img_type = $image_stats[2];

$ratio = ($imagewidth / $new_width);

$new_height = round($imageheight / $ratio);

if (!file_exists($Thumbpath."/".$entry)) 

{

 if ($img_type=="2")

 {

 $src_img = imagecreatefromjpeg($Imagepath."/".$entry);

 $dst_img = imagecreate($new_width,$new_height);

imagecopyresized($dst_img,$src_img,0,0,0,0,$new_width,$new_height,imagesx($src_img),imagesy($src_img));

imagejpeg($dst_img, "$Thumbpath"."/$entry");

 }

 elseif  ($img_type=="3")

 {

 $dst_img=ImageCreate($new_width,$new_height);

 $src_img=ImageCreateFrompng($Imagepath."/".$entry);

ImageCopyResized($dst_img,$src_img,0,0,0,0,$new_width,$new_height,ImageSX($src_img),ImageSY($src_img));

 Imagepng($dst_img, "$Thumbpath"."/$entry");

 }

 elseif  ($img_type=="1")

 {

 $cfg_thumb_url=$cfg_fullsizepics_url;

 }

}

  echo "$entry";

  echo "";

  }

?> 


"Imagefiles" is a folder for storing the input image file. Such as:


simple image.jpg

 

"Thumbfiles" is a folder for storing the thumbnail image files. Such as:


thumbnail image.jpg
 

Output

The following shows the input image name:

converting image ti thumbnail output.jpg


Similar Articles