http://www.php.net/manual/de/ref.fileinfo.php
require_once("Config.inc.php");
require_once("Functions.inc.php");
require_once("Connection.inc.php");
//require_once("HashImage.inc.php");
//require_once("SimpleImage.inc.php");
class Image {
 /* helper function: Send headers and returns an image. */
	public function sendImage($filename, $browser_cache) {
		
		$func	 			= new Functions();
		$imageRetArray 		= $func->getScreenResolutionFromUA();
				
		$resolutions		= array(2000, 1440, 1024, 1382, 960, 760, 480, 320);  // the resolution break-points to use (screen widths, in pixels)
		$jpg_quality   		= $imageRetArray["picQuality"]; // the quality of any generated JPGs on a scale of 0 to 100
		//$sharpen       		= TRUE; // Shrinking images can blur details, perform a sharpen on re-scaled images?
		//$watch_cache   		= TRUE; // check that the adapted image isn't stale (ensures updated source images are re-cached)
		$browser_cache 		= 31536000; // How long the BROWSER cache should last (seconds, minutes, hours, days. 7days by default)
		
		$myfilemtime		= filemtime($filename);
		$headers 			= $func->request_headers();
		$image_mime 		= image_type_to_mime_type(exif_imagetype($filename));
		$list 				= explode("/", $image_mime);
		$extension 			= $list[1];
		
		//$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
		if (in_array($extension, array('png', 'gif', 'jpeg'))) {
			header("Content-Type: image/".$extension);
		} else {
			header("Content-Type: image/jpeg");
		}
		header("Cache-Control: private, max-age=".$browser_cache);
		header('Expires: '.gmdate('D, d M Y H:i:s', time()+$browser_cache).' GMT');
		header('Content-Length: '.filesize($filename));
		
		// Checking if the client is validating his cache and if it is current.
		if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == $myfilemtime)) {
			// Client's cache IS current, so we just respond '304 Not Modified'.
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', $myfilemtime).' GMT', true, 304);
		} else {
			// Image not cached or cache outdated, we respond '200 OK' and output the image.
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', $myfilemtime).' GMT', true, 200);
			//header('Content-Length: '.filesize($fn));
		}
		
		readfile($filename);
		exit();
	}
	
	/* sharpen images function */
	public function findSharp($intOrig, $intFinal) {
	  $intFinal = $intFinal * (750.0 / $intOrig);
	  $intA     = 52;
	  $intB     = -0.27810650887573124;
	  $intC     = .00047337278106508946;
	  $intRes   = $intA + $intB * $intFinal + $intC * $intFinal * $intFinal;
	  return max(round($intRes), 0);
	}
	
	 /* refreshes the cached image if it's outdated */
	public function refreshCache($source_file, $cache_file, $resolution) {
	  if (file_exists($cache_file)) {
		// not modified
		if (filemtime($cache_file) >= filemtime($source_file)) {
		  return $cache_file;
		}
		// modified, clear it
		unlink($cache_file);
	  }
	  return $this->generateImage($source_file, $cache_file, $resolution, 65);
	}
	
	/* generates the given cache file for the given source file with the given resolution */
	public function generateImage($source_file, $cache_file, $resolution, $quality) {
		
		$func	 			= new Functions();
		$imageRetArray 		= $func->getScreenResolutionFromUA();
		
		$resolutions		= array(2000, 1440, 1024, 1382, 960, 760, 480, 320);  // the resolution break-points to use (screen widths, in pixels)
		$jpg_quality   	= $imageRetArray["picQuality"]; // the quality of any generated JPGs on a scale of 0 to 100
		$sharpen       	= TRUE; // Shrinking images can blur details, perform a sharpen on re-scaled images?
		$watch_cache   	= TRUE; // check that the adapted image isn't stale (ensures updated source images are re-cached)
		$browser_cache 	= 31536000; // How long the BROWSER cache should last (seconds, minutes, hours, days. 7days by default)
		$image_mime 	= image_type_to_mime_type(exif_imagetype($source_file));
		$list 			= explode("/", $image_mime);
		$extension 		= $list[1];
		//echo "mime: $image_mime"; exit;
		//$extension = strtolower(pathinfo($source_file, PATHINFO_EXTENSION));
	  // Check the image dimensions
	  $dimensions   = getimagesize($source_file);
	  $width        = $dimensions[0];
	  $height       = $dimensions[1];
	  
	  // We need to resize the source image to the width of the resolution breakpoint we're working with
	  $ratio      = $height/$width;
	  $new_width  = $resolution;
	  $new_height = ceil($new_width * $ratio);
	  $dst        = ImageCreateTrueColor($new_width, $new_height); // re-sized image
	  
	  /*
		if (strstr($_SERVER['HTTP_USER_AGENT'], "Google") !== false){
			$dst        = ImageCreateTrueColor(640, 480); // re-sized image
			$sharpen 	= FALSE;
		} else {
			$dst        = ImageCreateTrueColor($new_width, $new_height); // re-sized image
		}
		*/
		
	  switch ($extension) {
		case 'png':
		  $src = @ImageCreateFromPng($source_file); // original image
		break;
		case 'gif':
		  $src = @ImageCreateFromGif($source_file); // original image
		break;
		default:
		  $src = @ImageCreateFromJpeg($source_file); // original image
		  ImageInterlace($dst, true); // Enable interlancing (progressive JPG, smaller size file)
		break;
	  }
	  if($extension=='png'){
		imagealphablending($dst, false);
		imagesavealpha($dst,true);
		$transparent = imagecolorallocatealpha($dst, 255, 255, 255, 127);
		imagefilledrectangle($dst, 0, 0, $new_width, $new_height, $transparent);
	  }
	  $textinfo 	= "Coole News gibts auf BuzzerStar.com";
	//  $img->text($textinfo,"./library/fonts/delicious.ttf", $fontsize, '#000000', 'bottom left', 0, -10);
//imagettftext($this->image, $font_size, $angle, $x, $y, $color, $font_file, $text);	 
	// imagettftext($dst, 12, 1, 0,-10, "./library/fonts/delicious.ttf", $angle, $x, $y, $color, $font_file, $text);
	  ImageCopyResampled($dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height); // do the resize in memory
	  ImageDestroy($src);
	  // sharpen the image?
	  // NOTE: requires PHP compiled with the bundled version of GD (see http://php.net/manual/en/function.imageconvolution.php)
	  if($sharpen == TRUE && function_exists('imageconvolution')) {
		$intSharpness = $this->findSharp($width, $new_width);
		$arrMatrix = array(
		  array(-1, -2, -1),
		  array(-2, $intSharpness + 12, -2),
		  array(-1, -2, -1)
		);
		imageconvolution($dst, $arrMatrix, $intSharpness, 0);
	  }
	 $cache_dir = dirname($cache_file);
	 //echo "cachedir=$cache_dir";
	  // does the directory exist already?
	  if (!is_dir($cache_dir)) { 
		if (!mkdir($cache_dir, 0755, true)) {
		 // echo "cache dir check !mkdir"; exit;
		  // check again if it really doesn't exist to protect against race conditions
		  if (!is_dir($cache_dir)) {
			// uh-oh, failed to make that directory
			ImageDestroy($dst);
			//echo("Failed to create cache directory: $cache_dir");
		  }
		}
	  }
	//  if (!is_writable($cache_dir)) {
	//	echo("The cache directory is not writable: $cache_dir"); 
	//  }
	  // save the new file in the appropriate path, and send a version to the browser
	  switch ($extension) {
		case 'png':
		  $gotSaved = ImagePng($dst, $cache_file);
		break;
		case 'gif':
		  $gotSaved = ImageGif($dst, $cache_file);
		break;
		default:
		  $gotSaved = ImageJpeg($dst, $cache_file, $jpg_quality);
		break;
	  }
	  ImageDestroy($dst);
/*
		$func	 			= new Functions();
		$imageRetArray 		= $func->getScreenResolutionFromUA();
		$x 					= $imageRetArray["x"];
		$y 					= $imageRetArray["y"];
	  $thumb = new Imagick();
	  $thumb->readImage($cache_file);    
	 // $thumb->resizeImage($x,$y,Imagick::FILTER_CATROM,0,TRUE);
	  $thumb->adaptiveResizeImage($x,$y,TRUE);
	  $thumb->writeImage($cache_file);
	  $thumb->destroy(); 
*/	
 
	//  if (!$gotSaved && !file_exists($cache_file)) {
	//	echo("Failed to create image: $cache_file"); exit;
	 // }
	
	// Do we need to downscale the image?
	  if ($width <= $resolution) { // no, because the width of the source image is already less than the client width
		return $source_file;
	  }
	  
	  return $cache_file;
	}
	
public function downloadPictureExtra($pictureUri, $lang, $pic_desc, $pic_shortcode ){
	
	define("FILE_PUT_CONTENTS_ATOMIC_TEMP", "/tmp"); // dirname(__FILE__)."/cache"); 
	define("FILE_PUT_CONTENTS_ATOMIC_MODE", 0777); 
	
	$config 			= new Config();
	$func	 			= new Functions();
	$conn				= new Connection();
	$pdo				= $conn->prepareQuery();
		
	if (!is_dir(FILE_PUT_CONTENTS_ATOMIC_TEMP)) {
		mkdir( FILE_PUT_CONTENTS_ATOMIC_TEMP, FILE_PUT_CONTENTS_ATOMIC_MODE, true );
	}
	
	$temp = tempnam(FILE_PUT_CONTENTS_ATOMIC_TEMP, 'temp'); 
	if (!($f = @fopen($temp, 'w'))) { 
		$temp = FILE_PUT_CONTENTS_ATOMIC_TEMP . DIRECTORY_SEPARATOR . uniqid('temp'); 
		if (!($f = @fopen($temp, 'w'))) { 
			trigger_error("file_put_contents_atomic() : error writing temporary file '$temp'", E_USER_WARNING); 
			return false; 
		} 
	} 
   		
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 2);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
	//curl_setopt($ch,CURLOPT_SSLVERSION,3);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_URL, $pictureUri);
	curl_setopt($ch, CURLOPT_TIMEOUT, 1);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,1);
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	curl_setopt($ch, CURLOPT_AUTOREFERER, true);
	curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
	curl_setopt($ch, CURLOPT_HEADER, 0); 
	curl_setopt($ch, CURLOPT_FILE, $f);
	curl_exec($ch);
/*	if(curl_errno($ch)){
		echo 'Class Image - Line 54 -> error:' . curl_error($ch);
		echo "Error Downloading : ^$pictureUri^
";
	}
*/
	curl_close($ch);
	fclose($f); 
	
	$pictureExtension 	= pathinfo($pictureUri, PATHINFO_EXTENSION);
	$pictureId 			= $func->randomString();
		
	$pictureStorepath	= $config->picture_storepath();
	$newPicture			= $pictureId.".".$pictureExtension;
	$filename			= "$pictureStorepath/$newPicture";
	
	if (!rename($temp, $filename)) { 
		unlink($filename); 
		rename($temp, $filename); 
	}	
	chmod($filename, FILE_PUT_CONTENTS_ATOMIC_MODE); 
	
	$pos = stripos($lang, 'de');
	if ($pos === false) {
		// english table
		//$table = $config->sql_tablename_publish_en();
		$table = $config->sql_tablename_publish_de();
	} else {
		// deutsch table
		$table = $config->sql_tablename_publish_de();
	}
			
	if (empty($pic_desc)){
		$title = "Ein cooles Bild aus dem Internet, schau es dir hier an. Du kannst es downloaden, teilen und ausdrucken.";
	} else {
		$title = $pic_desc;
	}
	
	$writePictureSqlCode = array(':p_title' => $title, ':p_filename' => $newPicture,':p_shortcode' => $pic_shortcode,':p_uri' =>$pictureUri,':p_hash' => $pictureId);
		
	$picttable = $config->sql_tablename_pictures();
	$conn->insertPicture($pdo,$picttable,$writePictureSqlCode);
		
	//echo "stored as: $filename
";
	return 1;
}
public function downloadPicture($pictureUri, $lang){
	define("FILE_PUT_CONTENTS_ATOMIC_TEMP", "/tmp"); 
	define("FILE_PUT_CONTENTS_ATOMIC_MODE", 0777); 
	
	$config 			= new Config();
	$func	 			= new Functions();
	$conn				= new Connection();
	$pdo				= $conn->prepareQuery();
		
	if (!is_dir(FILE_PUT_CONTENTS_ATOMIC_TEMP)) {
		mkdir( FILE_PUT_CONTENTS_ATOMIC_TEMP, FILE_PUT_CONTENTS_ATOMIC_MODE, true );
	}
	
	$temp = tempnam(FILE_PUT_CONTENTS_ATOMIC_TEMP, 'temp'); 
	if (!($f = @fopen($temp, 'w'))) { 
		$temp = FILE_PUT_CONTENTS_ATOMIC_TEMP . DIRECTORY_SEPARATOR . uniqid('temp'); 
		if (!($f = @fopen($temp, 'w'))) { 
			trigger_error("file_put_contents_atomic() : error writing temporary file '$temp'", E_USER_WARNING); 
			return false; 
		} 
	} 
   		
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 2);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
	//curl_setopt($ch,CURLOPT_SSLVERSION,3);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_URL, $pictureUri);
	curl_setopt($ch, CURLOPT_TIMEOUT, 1);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,1);
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	curl_setopt($ch, CURLOPT_AUTOREFERER, true);
	curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
	curl_setopt($ch, CURLOPT_HEADER, 0); 
	curl_setopt($ch, CURLOPT_FILE, $f);
	curl_exec($ch);
/*	if(curl_errno($ch)){
		echo 'Class Image - Line 54 -> error:' . curl_error($ch);
		echo "Error Downloading : ^$pictureUri^
";
	}
*/
	curl_close($ch);
	fclose($f); 
	
	$pictureExtension 	= pathinfo($pictureUri, PATHINFO_EXTENSION);
	$pictureId 			= $func->randomString();
		
	$pictureStorepath	= $config->picture_storepath();
	$newPicture			= $pictureId.".".$pictureExtension;
	$filename			= "$pictureStorepath/$newPicture";
	
	if (!rename($temp, $filename)) { 
		unlink($filename); 
		rename($temp, $filename); 
	}	
	chmod($filename, FILE_PUT_CONTENTS_ATOMIC_MODE); 
	
	$pos = stripos($lang, 'de');
	if ($pos === false) {
		// english table
		//$table = $config->sql_tablename_publish_en();
		$table = $config->sql_tablename_publish_de();
	} else {
		// deutsch table
		$table = $config->sql_tablename_publish_de();
	}
		
	$stmt = $pdo->prepare("SELECT p_picture_1_description,p_shortcode FROM $table WHERE p_picture1=:picture LIMIT 1");
	$stmt->bindValue(':picture', $pictureUri, PDO::PARAM_STR);
	$stmt->execute();
	$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
	// DEBUG: print_r($stmt->errorInfo());
	
	if (empty($rows[0]["p_picture_1_description"])){
		$title = "Ein cooles Bild aus dem Internet, schau es dir hier an. Du kannst es downloaden, teilen und ausdrucken.";
	} else {
		$title = $rows[0]["p_picture_1_description"];
	}
	
	$writePictureSqlCode = array(':p_title' => $title, ':p_filename' => $newPicture,':p_shortcode' => $rows[0]["p_shortcode"],':p_uri' => $pictureUri,':p_hash' => $pictureId);
		
	$picttable = $config->sql_tablename_pictures();
	$conn->insertPicture($pdo,$picttable,$writePictureSqlCode);
		
	return 1;
}
public function checkHeader($pictureUri){
/*
	// is cURL installed yet?
    if (!function_exists('curl_init')){
        die('Sorry cURL is not installed!');
    }
*/	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 2);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
	//curl_setopt($ch,CURLOPT_SSLVERSION,3);
	
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_URL, $pictureUri);
	curl_setopt($ch, CURLOPT_TIMEOUT,1);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,1);
	//curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	curl_setopt($ch, CURLOPT_AUTOREFERER, true);
	curl_setopt($ch, CURLOPT_HEADER, true); 
	curl_setopt($ch, CURLOPT_NOBODY, true);
	$content 		= curl_exec ($ch);
	$contentType 	= curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
	curl_close($ch);
	
	//echo "pictureUri=$pictureUri;contentType=$contentType
";
	//$matches  		= preg_grep ('/image/i', $contentType);
	$pos = stripos($contentType, 'image');
	if ($pos === false) {
		return 0;
	} else {
		return 1;
	}
}
public function getExtension($pictureUri){
	$imageArray = array ( 'gif', 'jpeg', 'png','swf','psd','bmp','tiff', 'tiff','jpc','jp2','jpf','jb2','swc','aiff','wbmp','xbm');
								
	$path_info 	= pathinfo($pictureUri);
	return trim(strtolower($path_info['extension'])); // "bill"
}
public function checkExtension($pictureUri){
	$imageArray = array ( 'gif', 'jpeg', 'png','swf','psd','bmp','tiff', 'tiff','jpc','jp2','jpf','jb2','swc','aiff','wbmp','xbm');
								
	$path_info 	= pathinfo($pictureUri);
	$ext 		= trim(strtolower($path_info['extension'])); // "bill"
//	echo "extension=$key und $ext
";
	if (in_array($ext, $imageArray)){
		return 1;
	} else {
		return 0;
	}
}
public function text($text, $font_file, $font_size, $color, $position, $x_offset = 0, $y_offset = 0, $filename) {
		$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
		switch (strtolower($extension)) {
			case 'gif':
				$image = imagecreatefromgif($filename);
				break;
			case 'jpeg':
				$image = imagecreatefromjpeg($filename);
				break;
			case 'png':
				$image = imagecreatefrompng($filename);
				break;
			default:
				throw new Exception('Invalid image: '.$this->filename);
				break;
		}
					
		// todo - this method could be improved to support the text angle
		$angle = 0;
		
		// Determine text color
		$rgba = $this->normalize_color($color);
		$color = imagecolorallocatealpha($image, $rgba['r'], $rgba['g'], $rgba['b'], $rgba['a']);
		
		// Determine textbox size
		$box = imagettfbbox($font_size, $angle, $font_file, $text);
		if (!$box) {
			throw new Exception('Unable to load font: '.$font_file);
		}
		$box_width = abs($box[6] - $box[2]);
		$box_height = abs($box[7] - $box[1]);
		
		// Determine position
		switch (strtolower($position)) {
			case 'top left':
				$x = 0 + $x_offset;
				$y = 0 + $y_offset + $box_height;
				break;
			case 'top right':
				$x = $this->width - $box_width + $x_offset;
				$y = 0 + $y_offset + $box_height;
				break;
			case 'top':
				$x = ($this->width / 2) - ($box_width / 2) + $x_offset;
				$y = 0 + $y_offset + $box_height;
				break;
			case 'bottom left':
				$x = 0 + $x_offset;
				$y = $this->height - $box_height + $y_offset + $box_height;
				break;
			case 'bottom right':
				$x = $this->width - $box_width + $x_offset;
				$y = $this->height - $box_height + $y_offset + $box_height;
				break;
			case 'bottom':
				$x = ($this->width / 2) - ($box_width / 2) + $x_offset;
				$y = $this->height - $box_height + $y_offset + $box_height;
				break;
			case 'left':
				$x = 0 + $x_offset;
				$y = ($this->height / 2) - (($box_height / 2) - $box_height) + $y_offset;
				break;
			case 'right';
				$x = $this->width - $box_width + $x_offset;
				$y = ($this->height / 2) - (($box_height / 2) - $box_height) + $y_offset;
				break;
			case 'center':
			default:
				$x = ($this->width / 2) - ($box_width / 2) + $x_offset;
				$y = ($this->height / 2) - (($box_height / 2) - $box_height) + $y_offset;
				break;
		}
		
		// Add the text
		imagettftext($image, $font_size, $angle, $x, $y, $color, $font_file, $text);
		
		switch (strtolower($extension)) {
			case 'gif':
				imagegif($image);
				break;
			case 'jpeg':
				imagejpeg($image, null, round(80)); // 80 = quality
				break;
			case 'png':
				imagepng($image, null, round(9 * 80 / 100));
				break;
			default:
				throw new Exception('Unsupported image format: '.$this->filename);
				break;
		}
		
		return $filename;
	}
} // public class Image(){
?>