All pastes #957434 Raw Edit

PFimagefile

public php v1 · immutable
#957434 ·published 2008-03-25 23:44 UTC
rendered paste body
<?php/**************************************************************************\* Copyright 2006-2007 Loopshot Inc.                                        ** Written by:  Eric Jennings                                               ** <ericj@loopshot.com>                                                     ** --------------------------------------------                             **  This program is free software; you can redistribute it and/or modify it **  under the terms of the GNU Lesser General Public License as published   **  by the Free Software Foundation; either version 2 of the License, or    **  (at your option) any later version.                                     *\**************************************************************************//** * PFFactory * * @package * @version $id$ * @copyright 2006-2007 Loopshot Inc. * @author Eric Jennings <ericj@loopshot.com> * @license MIT License {@link http://www.opensource.org/licenses/mit-license.php} */class PFImageFile {	static private $instance;	public $upload_dir;		static $resize_max_width_small 		= 75;	static $resize_max_height_small 	= 75;	static $resize_max_width_med 		= 150;	static $resize_max_height_med 		= 150;	static $resize_max_width_large 		= 250;	static $resize_max_height_large 	= 250;		static $thumbnail_background		= '#FFFFFF';		private function __construct() {		$this->upload_dir = PF_BASE.'/modules';		//$this->registeredClasses = array();	}	static public function GetInstance() {		if(self::$instance == NULL) {			self::$instance = new PFImageFile();		}		return self::$instance;	}		static function SetLargeHeight($int){		self::$resize_max_height_large = $int;	}	static function SetLargeWidth($int){		self::$resize_max_width_large = $int;	}		static function SetMediumWidth($int){		self::$resize_max_width_med = $int;	}		static function SetMediumHeight($int){		self::$resize_max_height_med = $int;	}		static function SetSmallHeight($int){		self::$resize_max_height_small = $int;	}		static function SetSmallWidth($int){		self::$resize_max_width_small = $int;	}		static function SetBackground($hex){		self::$thumbnail_background = $hex;	}		public function GetUploadDir($module = 'shop'){		return $this->upload_dir.'/'.$module.'/misc/images/';	}	static public function ConvertNonstandardImageToJpeg($filePath) {		//printr($filePath);		//$type = exif_imagetype($filePath);		$type = self::GetCommandLineImageMimetype($filePath);		//printr('Type: '.$type);		if (empty($type)) {			throw new PFException('api', 'ATTEMPT_TO_CONVERT_UNSUPPORTED_IMAGE_TYPE_FAILED', E_USER_WARNING);		}		if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_JPEG || $type == IMAGETYPE_PNG) {			// these images display fine in the browser, don't degrade quality by needless conversion			// but we will swap suffixes in case somebody uploaded a wrong/missing suffix			switch ($type) {				case IMAGETYPE_JPEG:					// Quick fix.					// Appending .jpg breaks when we have an image that is a jpg but doesn't end in .jpg					// Since that file is uploaded we return a name for a file that doesn't exist					// So we will just rename our uploaded file to .jpg so that our return actually					// points to a file that exists. There is probably a better solution to this problem.					rename($filePath,self::StripFileExtension($filePath) . '.jpg');					return basename(self::StripFileExtension($filePath) . '.jpg');					break;				case IMAGETYPE_GIF:					return basename(self::StripFileExtension($filePath) . '.gif');					break;				case IMAGETYPE_PNG:					return basename(self::StripFileExtension($filePath) . '.png');					break;			}		}		// we know netpbm works with these types.  Other ones it doesn't do so well with		if ($type == IMAGETYPE_BMP || $type == IMAGETYPE_TIFF_II || $type == IMAGETYPE_TIFF_MM) {			$baseName = self::StripFileExtension($filePath) . '.jpg';			exec(PF_ANYTOPNM_EXECUTABLE_PATH . " $filePath | " . PF_PNMTOJPEG_EXECUTABLE_PATH . " > $baseName", $output, $returnValue);		/*			printr('Command: ' . PF_ANYTOPNM_EXECUTABLE_PATH . " $filePath | " . PF_PNMTOJPEG_EXECUTABLE_PATH . " > $baseName");			echo 'Command output: ';			printr($output);			printr('Return Value: ' . $returnValue);			printr('Old filename: ' . $filePath);			printr('Old MIME type: ' . $type);			printr('New filename: ' . $baseName);			printr('New MIME type: ' . self::GetCommandLineImageMimetype($baseName));			*/			if ($returnValue == 0) {				// now remove old file				self::UnlinkFile($filePath);				return basename($baseName);			} else {				throw new PFException('api', 'ATTEMPT_TO_CONVERT_UNSUPPORTED_IMAGE_TYPE_FAILED', E_USER_WARNING);			}		}		return false;	}	public static function CreateThumbnail($name, $filename, $newWidth, $newHeight) {		//$system = explode('.', $name);		//printr($name);		$type = self::GetCommandLineImageMimetype($name);		//printr($type);		switch ($type) {			case IMAGETYPE_JPEG:				$sourceImage = imagecreatefromjpeg($name);				break;			case IMAGETYPE_GIF:				$sourceImage = imagecreatefromgif($name);				break;			case IMAGETYPE_PNG:				$sourceImage = imagecreatefrompng($name);				break;			default:				throw new PFException('api', 'IMAGE_TYPE_MUST_BE_JPG_GIF_PNG', E_USER_WARNING);				break;		}		/*		if (preg_match('/jpg|jpeg/', $system[count($system)-1])) {			$sourceImage = imagecreatefromjpeg($name);		}		elseif (preg_match('/gif/', $system[count($system)-1])) {			$sourceImage = imagecreatefromgif($name);		}		elseif (preg_match('/png/', $system[count($system)-1])) {			$sourceImage = imagecreatefrompng($name);		}		else {			throw new PFException('api', 'IMAGE_TYPE_MUST_BE_JPG_GIF_PNG', E_USER_WARNING);		}*/		if (!isset($sourceImage)) {			throw new PFException('api', 'IMAGE_MIME_TYPE_NOT_FOUND', E_USER_ERROR);		}		$oldX = imageSX($sourceImage);		$oldY = imageSY($sourceImage);		if ($oldX > $oldY) {			$thumbWidth = $newWidth;			$thumbHeight = $oldY * ($newHeight / $oldX);		}		if ($oldX < $oldY) {			$thumbWidth = $oldX * ($newWidth / $oldY);			$thumbHeight = $newHeight;		}		if ($oldX == $oldY) {			$thumbWidth = $newWidth;			$thumbHeight = $newHeight;		}		$destinationImage = ImageCreateTrueColor($thumbWidth, $thumbHeight);		imagecopyresampled($destinationImage, $sourceImage, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $oldX, $oldY);		switch ($type) {			case IMAGETYPE_JPEG:				imagejpeg($destinationImage, $filename, 95);				break;			case IMAGETYPE_GIF:				imagegif($destinationImage, $filename);				break;			case IMAGETYPE_PNG:				imagepng($destinationImage, $filename);				break;			default:				throw new PFException('api', 'IMAGE_TYPE_MUST_BE_JPG_GIF_PNG', E_USER_WARNING);				break;		}/*		if (preg_match('/png/', $system[count($system)-1])) {			imagepng($destinationImage, $filename);		} elseif (preg_match('/gif/', $system[count($system)-1])) {			imagegif($destinationImage, $filename);		} elseif (preg_match('/jpg/', $system[count($system)-1]) || preg_match('/jpeg/', $system[count($system)-1])) {			imagejpeg($destinationImage, $filename, 95);		} else {			throw new PFException('api', 'IMAGE_TYPE_MUST_BE_JPG_GIF_PNG', E_USER_WARNING);		}*/		imagedestroy($destinationImage);		imagedestroy($sourceImage);	}	public static function IsImageMimetypeValid($fileName, $mimeType) {		if (empty($_FILES[$fileName]['mimetype'])) {			return true;		}		// check for exact match		if (in_array($mimeType, $this->attributes['mimetype'])) {			return true;		}		// check for *-pattern like image/*		list($major)	=	explode('/', $mimeType);		foreach ($this->attributes['mimetype'] as $m) {			$m =	explode('/', $m);			if ($m[1] == '*' && $m[0] == $major) {				return true;			}		}		return false;	}	public static function GetCommandLineImageMimetype($filePath) {		exec(PF_FILE_EXECUTABLE_PATH . " -i $filePath", $output, $returnValue);		$mime = explode(' ', $output[0]);		if ($returnValue == 0) {			switch ($mime[1]) {				case 'image/jpeg':					return IMAGETYPE_JPEG;					break;				case 'image/gif':					return IMAGETYPE_GIF;					break;				case 'image/png':					return IMAGETYPE_PNG;					break;				case 'image/x-ms-bmp':				case 'image/bmp':					return IMAGETYPE_BMP;					break;				case 'image/tiff':					return IMAGETYPE_TIFF_II;					break;				default:					return 0;					break;			}		} else {			throw new PFException('api', 'ATTEMPT_TO_CONVERT_UNSUPPORTED_IMAGE_TYPE_FAILED', E_USER_WARNING);		}	}		/* Pass in an array of allowed types.  Types are as follows:		IMAGETYPE_GIF		IMAGETYPE_JPEG		IMAGETYPE_PNG		IMAGETYPE_SWF		IMAGETYPE_PSD		IMAGETYPE_BMP		IMAGETYPE_TIFF_II (intel byte order)		IMAGETYPE_TIFF_MM (motorola byte order)		IMAGETYPE_JPC		IMAGETYPE_JP2		IMAGETYPE_JPX		IMAGETYPE_JB2		IMAGETYPE_SWC		IMAGETYPE_IFF		IMAGETYPE_WBMP		IMAGETYPE_XBM		PFImageFile::IsImageExifValid('/some/file.txt', array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG));	*/	static public function IsImageExifValid($filePath, $allowedTypes) {		foreach($allowedTypes as $type) {			if (exif_imagetype($filePath) == $type) {				return true;			}		}		return false;	}	public static function UnlinkFile($filename) {		// if files uploaded, let's get rid of it		if (file_exists(TR_ITEM_IMAGE_BASE_DIRECTORY . '/fullsize/' . $filename)) {			unlink(TR_ITEM_IMAGE_BASE_DIRECTORY . '/fullsize/' . $filename);		}		if (file_exists(TR_ITEM_IMAGE_BASE_DIRECTORY . '/thumbnail/' . $filename)) {			unlink(TR_ITEM_IMAGE_BASE_DIRECTORY . '/fullsize/' . $filename);		}	}	public static function StripFileExtension($filename) {		$ext = strrchr($filename, '.');		if($ext !== false) {			$filename = substr($filename, 0, -strlen($ext));		}		return $filename;	}	public static function GetRealValueOfMaxSize($maxFileSize) {		if (substr($maxFileSize, -1, 1) == 'G') {			$maxFileSize = substr($maxFileSize, 0, count($maxFileSize)) . '000000000';		} elseif (substr($maxFileSize, -1, 1) == 'M') {			$maxFileSize = substr($maxFileSize, 0, count($maxFileSize)) . '000000';		} elseif (substr($maxFileSize, -1, 1) == 'K') {			$maxFileSize = substr($maxFileSize, 0, count($maxFileSize)) . '000';		}		return $maxFileSize;	}	public static function IsImageLarger($name,$width, $height){		$type = self::GetCommandLineImageMimetype($name);		//printr($type);		switch ($type) {			case IMAGETYPE_JPEG:				$sourceImage = imagecreatefromjpeg($name);				break;			case IMAGETYPE_GIF:				$sourceImage = imagecreatefromgif($name);				break;			case IMAGETYPE_PNG:				$sourceImage = imagecreatefrompng($name);				break;			default:				throw new PFException('api', 'IMAGE_TYPE_MUST_BE_JPG_GIF_PNG', E_USER_WARNING);				break;		}		if (!isset($sourceImage)) {			throw new PFException('api', 'IMAGE_MIME_TYPE_NOT_FOUND', E_USER_ERROR);		}		$image_x = imageSX($sourceImage);		$image_y = imageSY($sourceImage);		if ($image_x > $width || $image_y > $height){			return true;		}		else{			return false;		}	}		/*		Got this code from another script, i'd like to clean it up and make it more scalable later.  -Jason			 */		public static function GenerateThreeThumbnails($el, $module = 'shop'){			$photo_ex_width 	= self::$resize_max_width_large;			$photo_ex_height 	= self::$resize_max_height_large;			$photo_med_width 	= self::$resize_max_width_med;			$photo_med_height 	= self::$resize_max_height_med;			$photo_small_width 	= self::$resize_max_width_small;			$photo_small_height = self::$resize_max_height_small;						if(!is_object($el) || !$el->GetValue()){				return false;			}						$path = PF_BASE.'/modules/'.$module.'/misc/images/';			$tmpfile = $path.$el->GetValue();						$cmd 		= 'file -b '.$tmpfile;			$filetype 	= strtolower(exec($cmd));			switch(TRUE){				case strstr($filetype, 'jpeg' ):					$extension = '.jpeg';				break;				case strstr($filetype, 'jpg'):					$extension = '.jpeg';						break;				case strstr($filetype, 'gif'):					$extension = '.gif';						break;				case strstr($filetype, 'png'):					$extension = '.png';				break;				default:					return false;				break;			}			mt_srand((double) microtime() * 100000);			$photo_name = substr(md5(time().mt_rand(0,100)),0,15);			$folder = substr($photo_name,0,2);			if(!file_exists($path."/".$folder))				mkdir($path."/".$folder,0777);			$folder.= "/".substr($photo_name,2,2);			if(!file_exists($path."/".$folder))				mkdir($path."/".$folder,0777);			$folder.= "/".substr($photo_name,4,2);			if(!file_exists($path."/".$folder))				mkdir($path."/".$folder,0777);			$photo["ex"]    = $folder."/".$photo_name.$extension;			$photo["med"]   = $folder."/".$photo_name."_med.jpeg";			$photo["small"] = $folder."/".$photo_name."_small.jpeg";				copy($tmpfile,$path."/".$photo["ex"]);			chmod($path."/".$photo["ex"], 0644);			list($ex_width,$ex_height) = getimagesize($path."/".$photo["ex"]);			//landscape image or square			if($ex_width >= $ex_height){				if($ex_width > $photo_ex_width){					$ds_width_ex  = $photo_ex_width;								$ratio_ex     = $ex_width / $ds_width_ex;							$ds_height_ex = $ex_height / $ratio_ex;					$ds_height_ex = round($ds_height_ex);					if($ds_height_ex > $photo_ex_height)						$ds_height_ex = $photo_ex_height;				}//if				else{					$ds_width_ex  = $ex_width;					$ds_height_ex = $ex_height;				}//else				if($ex_width > $photo_med_width){					$ds_width_med  = $photo_med_width;					$ratio_med     = $ex_width / $ds_width_med;					$ds_height_med = $ex_height / $ratio_med;					$ds_height_med = round($ds_height_med);					if($ds_height_med > $photo_med_height)						$ds_height_med = $photo_med_height;				}//if				else{					$ds_width_med  = $ex_width;					$ds_height_med = $ex_height;				}//else				if($ex_width > $photo_small_width){					$ds_width_small  = $photo_small_width;					$ratio_small     = $ex_width / $ds_width_small;					$ds_height_small = $ex_height / $ratio_small;					$ds_height_small = round($ds_height_small);					if($ds_height_small > $photo_small_height)						$ds_height_small = $photo_small_height;				}//if				else{					$ds_width_small  = $ex_width;					$ds_height_small = $ex_height;				}//else			}//if			//portrait image			elseif($ex_width < $ex_height){				if($ex_height > $photo_ex_height){					$ds_height_ex = $photo_ex_height;					$ratio_ex     = $ex_height / $ds_height_ex;					$ds_width_ex  = $ex_width / $ratio_ex;					$ds_width_ex  = round($ds_width_ex);					if($ds_width_ex > $photo_ex_width)						$ds_width_ex = $photo_ex_width;				}//if				else{					$ds_width_ex  = $ex_width;					$ds_height_ex = $ex_height;				}//else				if($ex_height > $photo_med_height){					$ds_height_med = $photo_med_height;					$ratio_med     = $ex_height / $ds_height_med;					$ds_width_med  = $ex_width / $ratio_med;					$ds_width_med  = round($ds_width_med);					if($ds_width_med > $photo_med_width)						$ds_width_med = $photo_med_width;				}//if				else{					$ds_width_med  = $ex_width;					$ds_height_med = $ex_height;				}//else				if($ex_height > $photo_small_height){					$ds_height_small = $photo_small_height;					$ratio_small     = $ex_height / $ds_height_small;					$ds_width_small  = $ex_width / $ratio_small;					$ds_width_small  = round($ds_width_small);					if($ds_width_small > $photo_small_width)						$ds_width_small = $photo_small_width;				}//if				else{					$ds_width_small  = $ex_width;					$ds_height_small = $ex_height;				}//else			}//elseif			$x_ex = round((($photo_ex_width - $ds_width_ex)/2));			if($x_ex == 0)				$x_ex = 1;			$y_ex = round((($photo_ex_height - $ds_height_ex)/2));			if($y_ex == 0)				$y_ex = 1;			$x_med = round((($photo_med_width - $ds_width_med)/2));			if($x_med == 0)				$x_med = 1;			$y_med = round((($photo_med_height - $ds_height_med)/2));			if($y_med == 0)				$y_med = 1;			$x_small = round((($photo_small_width - $ds_width_small)/2));			if($x_small == 0)				$x_small = 1;			$y_small = round((($photo_small_height - $ds_height_small)/2));			if($y_small == 0)				$y_small = 1;			if($extension == ".gif"){				$src = ImageCreateFromGif($path."/".$photo["ex"]);					}//if			elseif($extension == ".jpeg"){				$src = ImageCreateFromJpeg($path."/".$photo["ex"]);			}//elseif			elseif($extension == '.png'){				$src = ImageCreateFromPng($path.'/'.$photo['ex']);			}			$dst_ex    = ImageCreateTrueColor($photo_ex_width,$photo_ex_height);			$dst_med   = ImageCreateTrueColor($photo_med_width,$photo_med_height);			$dst_small = ImageCreateTrueColor($photo_small_width,$photo_small_height);						$rbg_array = self::HexToRGB(self::$thumbnail_background);						$white_ex    = ImageColorAllocate($dst_ex,$rbg_array['r'],$rbg_array['g'],$rbg_array['b']);			$white_med   = ImageColorAllocate($dst_med,$rbg_array['r'],$rbg_array['g'],$rbg_array['b']);			$white_small = ImageColorAllocate($dst_small,$rbg_array['r'],$rbg_array['g'],$rbg_array['b']);			ImageFilledRectangle($dst_ex,0,0,$photo_ex_width,$photo_ex_height,$white_ex);			ImageFilledRectangle($dst_med,0,0,$photo_med_width,$photo_med_height,$white_med);			ImageFilledRectangle($dst_small,0,0,$photo_small_width,$photo_small_height,$white_small);			ImageCopyResampled($dst_ex,$src,$x_ex,$y_ex,0,0,$ds_width_ex,$ds_height_ex,$ex_width,$ex_height);			ImageCopyResampled($dst_med,$src,$x_med,$y_med,0,0,$ds_width_med,$ds_height_med,$ex_width,$ex_height);			ImageCopyResampled($dst_small,$src,$x_small,$y_small,0,0,$ds_width_small,$ds_height_small,$ex_width,$ex_height);			if($extension == ".gif"){				ImageGif($dst_ex,$path."/".$photo["ex"]);			}//if			elseif($extension == ".jpeg"){				ImageJpeg($dst_ex,$path."/".$photo["ex"],80);			}			elseif($extension == '.png'){				ImagePng($dst_ex,$path.'/'.$photo['ex'],80);			}			ImageJpeg($dst_med,$path."/".$photo["med"],80);			ImageJpeg($dst_small,$path."/".$photo["small"],80);			ImageDestroy($src);			ImageDestroy($dst_ex);			ImageDestroy($dst_med);			ImageDestroy($dst_small);			$photo['name'] = $el->GetValue();			$photo['ex'] = '/modules/'.$module.'/misc/images/'.$photo['ex'];			$photo['med'] = '/modules/'.$module.'/misc/images/'.$photo['med'];			$photo['small'] = '/modules/'.$module.'/misc/images/'.$photo['small'];			return $photo;			}		static function HexToRGB($hex) {		$hex = ereg_replace("#", "", $hex);		$color = array();				if(strlen($hex) == 3) {			$color['r'] = hexdec(substr($hex, 0, 1) . $r);			$color['g'] = hexdec(substr($hex, 1, 1) . $g);			$color['b'] = hexdec(substr($hex, 2, 1) . $b);		}		else if(strlen($hex) == 6) {			$color['r'] = hexdec(substr($hex, 0, 2));			$color['g'] = hexdec(substr($hex, 2, 2));			$color['b'] = hexdec(substr($hex, 4, 2));		}				return $color;	}		static function RGBToHex($r, $g, $b) {		$hex = "#";		$hex.= dechex($r);		$hex.= dechex($g);		$hex.= dechex($b);				return $hex;	}}?>