<?php
defined('WikyBlog') or die('Not an entry point...');

/*

requires php 4.0.2+ for imagetypes()
requires $wbWritable w/out ftp  => if using ftp  /thumbnails directory needs to be writable



*/


class thumbnail{
	
	/* static */
	function createSquare($source_path,$dest_path,$size=50){
		$new_w = $new_h = $size;
		
		$src_img = thumbnail::getSrcImg($source_path);
		if( !$src_img ){
			return;
		}
		
		//Size
		$old_x = imageSX($src_img);
		$old_y = imageSY($src_img);
		
		//
		if( $old_x > $old_y ){
			$off_w = ($old_x - $old_y) / 2;
			$off_h = 0;
			$old_x = $old_y;
		}elseif( $old_y > $old_x ){
			$off_w = 0;
			$off_h = ($old_y - $old_x) / 2;
			$old_y = $old_x;
		}else{
			$off_w = 0;
			$off_h = 0;
		}
		
		thumbnail::createImg($src_img, $dest_path, 0, 0, $off_w, $off_h, $new_w, $new_h, $old_x, $old_y);
	}
	
	/* static */
	function getSrcImg($source_path){
		//get file type
		$nameParts = explode('.',$source_path);
		$file_type = array_pop($nameParts);
		$file_type = strtolower($file_type);
		
		$supported_types = imagetypes();
		
		
		//start
		$src_img = false;
		switch($file_type){
			case 'jpg':
			case 'jpeg':
				if( $supported_types & IMG_JPG ){
					return imagecreatefromjpeg($source_path);
				}
			break;
			case 'gif':
				return imagecreatefromgif($source_path);
			break;
			case 'png':
				if( $supported_types & IMG_PNG) {
					return imagecreatefrompng($source_path);
				}
			break;
			case 'bmp';
				if( $supported_types & IMG_WBMP) {
					return imagecreatefromwbmp($source_path);
				}
			break;
			default:
				//message('not supported for thumbnail: '.$file_type);
			return false;
		}
		return false;
	}
	
	function createImg($src_img, $dest_path, $dst_x, $dst_y, $off_w, $off_h, $new_w, $new_h, $old_x, $old_y){
	
		$dst_img = imagecreatetruecolor($new_w,$new_h);
		if( !$dst_img ){
			trigger_error('dst_img not created');
			return;
		}
		
		if( !imagecopyresampled($dst_img, $src_img, $dst_x, $dst_y, $off_w, $off_h, $new_w, $new_h, $old_x, $old_y) ){
			trigger_error('copyresample failed');
			imagedestroy($dst_img);
			imagedestroy($src_img);
			return;
		}

		//save all as jpg
		$dest_path .= '.jpg';
		imagejpeg($dst_img,$dest_path,90);
		
		imagedestroy($dst_img);
		imagedestroy($src_img);
	}		
	
}