<?php
//ver1.0 140713 @_untitle_d



$source_path = urldecode($_GET['src']);
list($source_width, $source_height, $source_type) = getimagesize($source_path);
if (!$source_type) die();

$_w = $_GET['w'];
$_h = $_GET['h'];
if ($_w){
	if (!$_h)
		$_h = (int)(($_w * $source_height) / $source_width);
}else{
	if ($_h){
		$_w = (int)(($_h * $source_width) / $source_height);
	}else{ 
		//$_w = $source_width;
		//$_h = $source_height;
		$_w = 50;
		$_h = 50; 
	}
}

$_q = $_GET['q'];
if (!$_q) $_q = 100;


switch ($source_type) {
    case IMAGETYPE_GIF:
        $source_gdim = imagecreatefromgif($source_path);
        break;
    case IMAGETYPE_JPEG:
        $source_gdim = imagecreatefromjpeg($source_path);
        break;
    case IMAGETYPE_PNG:
        $source_gdim = imagecreatefrompng($source_path);
        break;	
}

$source_aspect_ratio = $source_width / $source_height;
$desired_aspect_ratio = $_w / $_h;

if ($source_aspect_ratio > $desired_aspect_ratio) {
    /*
     * Triggered when source image is wider
     */
    $temp_height = $_h;
    $temp_width = (int)($_h * $source_aspect_ratio);
} else {
    /*
     * Triggered otherwise (i.e. source image is similar or taller)
     */
    $temp_width = $_w;
    $temp_height = (int)($_w / $source_aspect_ratio);
}

/*
 * Resize the image into a temporary GD image
 */

$temp_gdim = imagecreatetruecolor($temp_width, $temp_height);
imagecopyresampled(
    $temp_gdim,
    $source_gdim,
    0, 0,
    0, 0,
    $temp_width, $temp_height,
    $source_width, $source_height
);

/*
 * Copy cropped region from temporary image into the desired GD image
 */

$x0 = ($temp_width - $_w) / 2;
$y0 = ($temp_height - $_h) / 2;
$desired_gdim = imagecreatetruecolor($_w, $_h);
imagecopy(
    $desired_gdim,
    $temp_gdim,
    0, 0,
    $x0, $y0,
    $_w, $_h
);

/*
 * Render the image
 * Alternatively, you can save the image in file-system or database
 */

header('Content-type: image/jpeg');
imagejpeg($desired_gdim, '', $_q);

/*
 * Add clean-up code here
 */


/*
 * Crop-to-fit PHP-GD
 * http://911-need-code-help.blogspot.com/2009/04/crop-to-fit-image-using-aspphp.html
 *
 * Resize and center crop an arbitrary size image to fixed width and height
 * e.g. convert a large portrait/landscape image to a small square thumbnail
 */

?>