How to create Image Thumbnail component in cakephp

Cakephp

Posted on 04 Sep 15 by Vickey
  1477



Components provide us reusable code and logic that can be used into a controller. In cakephp we have number of core components like session, cookie, Auth and we can also create our custom component as per our requirement. In this blog I am going to create a component for creating a thumbnail image from a large image.

Step 1:- Create a file 'ImagethumbComponent' under /app/Controller/Component and add code

class ImagethumbComponent extends Component{

	function generateThumb( $src_path, $thumb_path, $thumb_width,$image_file_name ) 
	{
	
  		$src_dir 	= 	opendir( $src_path );

    	$img_path_info 	= 	pathinfo($src_path . $image_file_name);
    	if(strtolower($img_path_info['extension']) == 'jpg') 
		{
      		$image 	= 	imagecreatefromjpeg( "{$src_path}{$image_file_name}" );
		} 
		else if(strtolower($img_path_info['extension']) == 'png')
		{
	 		$image 	= 	imagecreatefrompng( "{$src_path}{$image_file_name}" );
		} 
		
		else if( strtolower($img_path_info['extension']) == 'gif'){
	 		$image 	= 	imagecreatefromgif( "{$src_path}{$image_file_name}" );
		} 
	 
	    $imgwidth = imagesx( $image );
	    $imgheight = imagesy( $image );
	    $new_thumb_width = $thumb_width;
	    $new_thumb_height = floor( $imgheight * ( $thumb_width / $imgwidth ) );
	    $temp_img = imagecreatetruecolor( $new_thumb_width, $new_thumb_height );
	    imagecopyresized( $temp_img, $image, 0, 0, 0, 0, $new_thumb_width, $new_thumb_height, $imgwidth, $imgheight );
	  
		if(strtolower($img_path_info['extension']) == 'jpg') 
		{
	      imagejpeg( $temp_img, "{$thumb_path}{$image_file_name}" );
		} 
		else if(strtolower($img_path_info['extension']) == 'png')
		{
		 	imagepng( $temp_img, "{$thumb_path}{$image_file_name}" );
		} 
		else  if ( strtolower($img_path_info['extension']) == 'gif' ){
		    imagegif( $temp_img, "{$thumb_path}{$image_file_name}" );
		} 
	}
}

here '$src_path' is path of directory of source image,  '$thumb_path' is path where new image will be save, '$thumb_width' is the width of thumb image and '$image_file_name' will the name of image file

Step 2:- How to use it

Open your controller in which you want to use it and add component

class UsersController extends AppController {

	public $components = array('Paginator','Imagethumb');

}

now call component function in your action

public function index() {

	$this->Imagethumb->generateThumb(WWW_ROOT .'uploads/', WWW_ROOT."uploads/uploadssmall_thumbs/",$thumb_img_width='100', $file_name='Music-tomasino.cz_.jpg');
}

here 'uploads' directory located under '/app/webroot' where your original image exist and thumb image will be save in 'uploadssmall_thumbs' directory


If this post help you reduce time to develop, you can help me to maintain this website :)
www.000webhost.com