<?php

defined('IN_SYSTEM') === false && exit('PHPnew Blog.');

function fun_imageresize($srcfile, $tow, $toh, $tofile = false){
    if (empty($tofile) === true)
        $tofile = fun_thumpath($srcfile);

    $info = "";
    if(is_file($srcfile) === false || $tow <= 0 || $toh <= 0 || !extension_loaded('gd'))
        return false;

    $data = getimagesize($srcfile, $info);
    switch ($data[2]) {
        case 1:
            $im = @imagecreatefromgif($srcfile);
            break;
        case 2:
            $im = @imagecreatefromjpeg($srcfile);
            break;
        case 3:
            $im = @imagecreatefrompng($srcfile);
            break;
    }
    
    if(empty($im) === true)
        return false;
        
    $srcw = $data[0];
    $srch = $data[1];
    
    if (($srcw > $tow) or ($srh > $toh)) {
        if (($srcw / $tow) >= ($srch / $toh)) {
            $temp_height = $toh;
            $temp_width = $srcw / ($srch / $toh);
            $src_x = abs(($tow - $temp_width) / 2);
            $src_y = 0;
        } else {
            $temp_width = $tow;
            $temp_height = $srch / ($srcw / $tow);
            $src_x = 0;
            $src_y = abs(($toh - $temp_height) / 2);
        }
        $temp_img = imagecreatetruecolor($temp_width, $temp_height);
            $a = imagecopyresampled ($temp_img, $im, 0, 0, 0, 0, $temp_width, $temp_height, $srcw,$srch);
        $ni = imagecreatetruecolor($tow, $toh);
            $b = imagecopyresampled ($ni, $temp_img, 0, 0, $src_x, $src_y, $tow, $toh, $tow, $toh);
        
        if(empty($a) === true || empty($b) === true)
            return false;
    
        if (function_exists('imagejpeg')){
            imagejpeg($ni, $tofile);
        }else{
           imagepng($ni, $tofile);  
        }
        imagedestroy($ni);
    }
    imagedestroy($im);
    return $tofile;
}

function  fun_thumpath($srcfile){
	return substr($srcfile, 0, -4) . "_small" . substr($srcfile, -4);
}