<?php

class Image{

	public static function toJpg($path){

		$infos = pathinfo($path);
		if($infos['extension']=='jpg' || $infos['extension']=='jpeg') return;
	
		//Make image with white background instead of black when converting png to jpg
		$input = self::resource($path);
		list($width, $height) = getimagesize($path);
		$output = imagecreatetruecolor($width, $height);
		$white = imagecolorallocate($output,  255, 255, 255);
		imagefilledrectangle($output, 0, 0, $width, $height, $white);
		imagecopy($output, $input, 0, 0, 0, 0, $width, $height);
	    // quality is a value from 0 (worst) to 100 (best)
		imagejpeg($output, $infos['dirname'].SLASH.$infos['filename'].'.jpg', 100);

		unlink($path);
	}

	public static function toPng($path){

		$infos = pathinfo($path);
		if($infos['extension']=='png') return;
	
		$input = self::resource($path);
		list($width, $height) = getimagesize($path);
		$output = imagecreatetruecolor($width, $height);
		$white = imagecolorallocate($output,  255, 255, 255);
		imagefilledrectangle($output, 0, 0, $width, $height, $white);
		imagecopy($output, $input, 0, 0, 0, 0, $width, $height);
	    // compression is a value from 0 (worst) to 9 (best)
		imagepng($output, $infos['dirname'].SLASH.$infos['filename'].'.png', 9);

		unlink($path);
	}

	public static function resize($path,$width,$height,$keepRatio = true){
		$resource = self::resource($path);
		$infos = pathinfo($path);

		$oldX =   imageSX($resource);
    	$oldY =   imageSY($resource);

    	if($oldX > $oldY) 
	    {
	        $thumb_w    =   $width;
	        $thumb_h    =   $oldY*($height/$oldX);
	    }
	    if($oldX < $oldY) 
	    {
	        $thumb_w    =   $oldX*($width/$oldY);
	        $thumb_h    =   $height;
	    }
	    if($oldX == $oldY) 
	    {
	        $thumb_w    =   $width;
	        $thumb_h    =   $height;
	    }

	    if(!$keepRatio){
			$thumb_w = $width;
			$thumb_h = $height;
	    }

	    $dst_resource = ImageCreateTrueColor($thumb_w,$thumb_h);
    	
    	if($infos['extension']=='png') {
    		$resource = ImageCreateFromPNG($path);
    		imagealphablending($dst_resource, false);
	    	imagecopyresampled($dst_resource,$resource,0,0,0,0,$thumb_w,$thumb_h,$oldX,$oldY); 
    		imagesavealpha($dst_resource, true);
    		$result = imagepng($dst_resource, $path, 6);
	    }
	    if($infos['extension']=='jpg' || $infos['extension']=='jpeg') {
	    	imagecopyresampled($dst_resource,$resource,0,0,0,0,$thumb_w,$thumb_h,$oldX,$oldY); 
	        $result = imagejpeg($dst_resource,$path,80);
	    }
	    imagedestroy($dst_resource); 
    	imagedestroy($resource);
	}

	public static function resource($path){
		$infos = pathinfo($path);
		switch ($infos['extension']){
			case 'jpg':
			case 'jpeg':
				return imagecreatefromjpeg($path);
			break;
			case 'png':
				return imagecreatefrompng($path);
			break;
			case 'gif':
				return imagecreatefromgif($path);
			break;
			case 'bmp':
				return imagecreatefrombmp($path);
			default:
			return 0;
			break;
		}
	}

}

?>