<?php

function createThumb($fname, $thumbWidth, $thumbHeight){
	$dir = scandir('images');
	
	if(!in_array($fname, $dir)){
		echo "Ошибка. Изображения не существует $fname";
	}
	else{
		$info = pathinfo("images/$fname");
		if(strtolower($info['extension']=='jpg')){
			
			$img = imagecreatefromjpeg("images/$fname");
			$width = imagesx($img);
			$height = imagesy($img);
			if($width<$thumbWidth && $height<$thumbHeight){
				continue;
			}
			if($width>$height){
			$new_width = $thumbWidth;
			$new_height=floor($height*($thumbWidth/$width));
		}

		   else{
		   	$new_height = $thumbHeight;
		   	$new_width = floor($width*($thumbHeight/$height));
		   }



			$tmp_img = imagecreatetruecolor($new_width, $new_height);
			imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
			header('Content-Type: image/jpg');
			imagejpeg($tmp_img, "thumbnails/$fname");
		}

		elseif(strtolower($info['extension']=='png')){
			
			$img = imagecreatefrompng("images/$fname");
			$width = imagesx($img);
			$height = imagesy($img);
			if($width<$thumbWidth && $height<$thumbHeight){
				continue;
			}
			if($width>$height){
			$new_width = $thumbWidth;
			$new_height=floor($height*($thumbWidth/$width));
		}

		   else{
		   	$new_height = $thumbHeight;
		   	$new_width = floor($width*($thumbHeight/$height));
		   }
			$tmp_img = imagecreatetruecolor($new_width, $new_height);
			imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
			header('Content-Type: image/png');
			imagepng($tmp_img, "thumbnails/$fname");
		}
	}
}

$fname = $_GET['fname'];
createThumb($fname, 100, 100);
