<?php

/*
extension=gd must be active/loaded
*/

class imageOptimzer{

	public $input;
	public $memoryImage;
	public $fileInfo;
	public $fileName;
	public $maxWidth;
	public $maxHeight;
	public $quality;


	public function __construct($source, $maxWidth=1000 , $maxHeight=1000, $quality=9){
		$this->input = $source["tmp_name"];
		$this->maxWidth = $maxWidth;
		$this->maxHeight = $maxHeight;
		$this->quality = $quality;
		$this->fileName = $source["name"];
		$this->fileInfo = $this->getImageInfo();
		$this->createImageFromInput($source);
		$thumb = $this->scaleImageDimensions();
		$this->createOutputImage($thumb);
	}

	public function getImageInfo(){
		return getimagesize($this->input);
	}

	public function createImageFromInput(){
		if ($this->fileInfo['mime'] == 'image/jpeg'){
			$this->memoryImage = imagecreatefromjpeg($this->input);
		}
		elseif ($this->fileInfo['mime'] == 'image/gif'){
			$this->memoryImage = imagecreatefromgif($this->input);
		}
		elseif ($this->fileInfo['mime'] == 'image/png'){
			$this->memoryImage = imagecreatefrompng($this->input);	
		}
		return $this->memoryImage;
	}

	public function scaleImageDimensions(){
		if( $this->maxWidth >= $this->fileInfo[0] && $this->maxHeight >= $this->fileInfo[1] ) {
	    	$ratio = 1;
	  	}elseif( $this->fileInfo[0] > $this->fileInfo[1] ) {
	    	$ratio = $this->maxWidth / $this->fileInfo[0];
	  	}else {
	    	$ratio = $this->maxHeight / $this->fileInfo[1];
	  	}
	  	$thumb_width = round( $this->fileInfo[0] * $ratio ); //get the smaller value from cal # floor()
		$thumb_height = round( $this->fileInfo[1] * $ratio );
		$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
		imagecopyresampled( $thumb, $this->memoryImage, 0, 0, 0, 0, $thumb_width, $thumb_height, $this->fileInfo[0], $this->fileInfo[1] );
	  	return $thumb;
	}

	public function createOutputImage($thumb){
		$file = pathinfo($this->fileName, PATHINFO_FILENAME);
		header('Content-Type: image/png');
		header('Content-Disposition: inline; filename="' . $file . '.png"');
		imagepng($thumb,null,$this->quality);
		imagedestroy($thumb);
	}


}



?>