<?php
error_reporting(0);
$cache_dir = 'dat/cache/';
$def_w = 160;
$def_h = 120;
$upimg = $_GET["p"];
$imgw = @intval($_GET["w"]);
$imgh = @intval($_GET["h"]);
$t = @intval($_GET["t"]);
$type = ($_GET["q"]==1) ? 'png' : 'jpg';
$typeh = ($_GET["q"]==1) ? 'png' : 'jpeg';
if (!$imgw) {
	$imgw = $def_w;
}
if (!$imgh) {
	$imgh = $def_h;
}
if (!$t) {
	$t = 0;
}
$upimg_c = str_replace('./dat/', '', $upimg);
$upimg_c = $cache_dir.str_replace('/', '', $upimg_c);
$upimg_c = str_replace('.jpg', $imgw.$imgh.'.'.$type, $upimg_c);
if (is_file($upimg_c)) {
	header("content-type: image/".$typeh);
	readfile($upimg_c);
	exit;
}
if(!is_file($upimg)){
	exit;
}

$img_info = getimagesize($upimg);
if($img_info){
	$x = 0;
	$y = 0;
	if ($t==1) {
		// 縦横比でトリミングサイズと上揃えを決定
		$size = array($img_info[0], floor($img_info[0] / $imgw * $imgh));
		$pos = array(0, 0);
		if ($size[1] > $img_info[1]) {
			$size = array(floor($img_info[1] / $imgh * $imgw), $img_info[1]);
			$pos = array(0, 0);
		}
	} elseif ($t==2) {
		// 縦横比でトリミングサイズと下揃えを決定
		$size = array($img_info[0], floor($img_info[0] / $imgw * $imgh));
		$pos = array(0, floor(($img_info[1] - $size[1])));
		if ($size[1] > $img_info[1]) {
			$size = array(floor($img_info[1] / $imgh * $imgw), $img_info[1]);
			$pos = array(floor(($img_info[0] - $size[0])), 0);
		}
	} else {
		// 縦横比でトリミングサイズとセンターを決定
		$size = array($img_info[0], floor($img_info[0] / $imgw * $imgh));
		$pos = array(0, floor(($img_info[1] - $size[1]) / 2));
		if ($size[1] > $img_info[1]) {
			$size = array(floor($img_info[1] / $imgh * $imgw), $img_info[1]);
			$pos = array(floor(($img_info[0] - $size[0]) / 2), 0);
		}
	}
	
	if($src_im = @imagecreatefromjpeg($upimg)){

		if($dist_im = @imagecreatetruecolor($imgw,$imgh)){
			$color = imagecolorallocate($dist_im, 255, 255, 255);
			imagefill($dist_im, 0,0, $color);
			imagecopyresampled($dist_im,$src_im,$x,$y,$pos[0],$pos[1],$imgw,$imgh,$size[0],$size[1]);
			header("content-type: image/".$typeh);
			if ($type=='png') {
				imagepng($dist_im, null, 6);
				imagepng($dist_im, $upimg_c, 6);
			} else {
				///OLD QUALITY VALUE IS 95, IT CHANGED TO 80 TO IMPROVE PAGE SPEED///				
				imagejpeg($dist_im, null, 80);
				imagejpeg($dist_im, $upimg_c, 80);
			}
			imagedestroy($dist_im);
			imagedestroy($src_im);
		}
	}
}
?>