Php代碼
1 <?php 2 /** 3 * 圖片類 4 * @author Haroldphp@163.com 5 * @version 1.0 6 * 7 */ 8 class image { 9 const ROOT_PATH = './'; 10 const FAIL_WRITE_DATA = 'Fail to write data'; 11 //沒有資料流 12 const NO_STREAM_DATA = 'The post data is empty'; 13 //圖片類型不正確 14 const NOT_CORRECT_TYPE = 'Not a correct image type'; 15 //不能建立檔案 16 const CAN_NOT_CREATE_FILE = 'Can not create file'; 17 //上傳圖片名稱 18 public $image_name; 19 //圖片儲存名稱 20 public $save_name; 21 //圖片儲存路徑 22 public $save_dir; 23 //目錄+圖片完整路徑 24 public $save_fullpath; 25 26 /** 27 * 建構函式 28 * @param String $save_name 儲存圖片名稱 29 * @param String $save_dir 儲存路徑名稱 30 */ 31 public function __construct($save_name, $save_dir) { 32 //set_error_handler ( $this->error_handler () ); 33 34 //設定儲存圖片名稱,若未設定,則隨機產生一個唯一檔案名 35 $this->save_name = $save_name ? $save_name : md5 ( mt_rand (), uniqid () ); 36 //設定儲存圖片路徑,若未設定,則使用年/月/日格式進行目錄存放 37 $this->save_dir = $save_dir ? self::ROOT_PATH .$save_dir : self::ROOT_PATH .date ( 'Y/m/d' ); 38 39 //建立檔案夾 40 @$this->create_dir ( $this->save_dir ); 41 //設定目錄+圖片完整路徑 42 $this->save_fullpath = $this->save_dir . '/' . $this->save_name; 43 } 44 //相容PHP4 45 public function image($save_name) { 46 $this->__construct ( $save_name ); 47 } 48 49 public function stream2Image() { 50 //位元據流 51 $data = file_get_contents ( 'php://input' ) ? file_get_contents ( 'php://input' ) : gzuncompress ( $GLOBALS ['HTTP_RAW_POST_DATA'] ); 52 //資料流不為空白,則進行儲存操作 53 if (! empty ( $data )) { 54 //建立並寫入資料流,然後儲存檔案 55 if (@$fp = fopen ( $this->save_fullpath, 'w+' )) { 56 fwrite ( $fp, $data ); 57 fclose ( $fp ); 58 $baseurl = "http://" . $_SERVER ["SERVER_NAME"] . ":" . $_SERVER ["SERVER_PORT"] . dirname ( $_SERVER ["SCRIPT_NAME"] ) . '/' . $this->save_name; 59 if ( $this->getimageInfo ( $baseurl )) { 60 echo $baseurl; 61 } else { 62 echo ( self::NOT_CORRECT_TYPE ); 63 } 64 } else { 65 66 } 67 } else { 68 //沒有接收到資料流 69 echo ( self::NO_STREAM_DATA ); 70 } 71 } 72 /** 73 * 建立檔案夾 74 * @param String $dirName 檔案夾路徑名 75 */ 76 public function create_dir($dirName, $recursive = 1,$mode=0777) { 77 ! is_dir ( $dirName ) && mkdir ( $dirName,$mode,$recursive ); 78 } 79 /** 80 * 擷取圖片資訊,返回圖片的寬、高、類型、大小、圖片mine類型 81 * @param String $imageName 圖片名稱 82 */ 83 public function getimageInfo($imageName = '') { 84 $imageInfo = getimagesize ( $imageName ); 85 if ($imageInfo !== false) { 86 $imageType = strtolower ( substr ( image_type_to_extension ( $imageInfo [2] ), 1 ) ); 87 $imageSize = filesize ( $imageInfo ); 88 return $info = array ('width' => $imageInfo [0], 'height' => $imageInfo [1], 'type' => $imageType, 'size' => $imageSize, 'mine' => $imageInfo ['mine'] ); 89 } else { 90 //不是合法的圖片 91 return false; 92 } 93 94 } 95 96 /*private function error_handler($a, $b) { 97 echo $a, $b; 98 }*/ 99 100 }