標籤:php微型架構
<?php
// 驗證碼類
class image {
protected $im;
protected $img_width;
protected $img_height;
protected $img_type;
// 產生隨機數
static public function randStr($n = 4) {
if($n <= 0) {
return ‘‘;
}
$str = ‘abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ0123456789‘;
$str = substr(str_shuffle($str),0,$n);
return $str;
}
// 產生驗證碼
static public function chkcode($w=60,$h=25) {
// $w 寬, $h 高
$code = self::randStr(4);
// 造畫布
$im = imagecreatetruecolor($w,$h);
$bak = imagecreatetruecolor($w,$h);
// 造顏色,灰底+藍字
$gray = imagecolorallocate($im,100,100,100);
$blue = imagecolorallocate($im,0,0,255);
$bak_gray = imagecolorallocate($bak,100,100,100);
// 填充
imagefill($im,0,0,$gray);
imagefill($bak,0,0,$bak_gray);
// 寫字
imagestring($im,5,10,5,$code,$blue);
/*****
把驗證碼儲存到session裡
*****/
/*****
把驗證碼的字元扭曲,供參考,不要求.
$niu = 3;
for($i=0;$i<60;$i++) {
// 按正弦Function ComputeY軸的波動
$y = sin(deg2rad((720/$w) * $i)) * $niu;
imagecopy($bak,$im,$i,$y,$i,0,1,$h);
}
*****/
header(‘content-type: image/jpeg‘);
imagejpeg($bak);
}
static public function make_thumb($ori,$w=200,$h=200) {
// 判斷原圖大小,如果原圖比縮減還小,不必處理.
// 讀出大圖當畫布
$info = self::getinfo($ori);
if($info[‘func‘] === false) {
return false;
}
$createfunc = ‘imagecreatefrom‘ . $info[‘func‘]; // 分析出讀取大圖所用的函數名.
$src = $createfunc($ori);
// 建立小畫布,並把背景做成灰色
$small = imagecreatetruecolor($w,$h);
$gray = imagecolorallocate($small,100,100,100);
imagefill($small,0,0,$gray);
// 複製大圖到小圖
$scale = min($w/$info[‘width‘], $h/$info[‘height‘]); // 以更小的縮小比例為準,才能裝下
// 根據比例,算最終複製過去的塊的大小.
$realw = $info[‘width‘] * $scale;
$realh = $info[‘height‘] * $scale;
// 產生小圖
/*
bool imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
*/
// 計算留白
$lw = round(($w - $realw)/2); // 計算左側留的寬度
$lh = round(($h - $realh)/2); // 計算上部留的高度
imagecopyresampled($small,$src,$lw,$lh,0,0,$realw,$realh,$info[‘width‘],$info[‘height‘]);
/*
header(‘content-type: image/jpeg‘);
imagejpeg($small);
*/
// 計算小圖片的儲存路徑
$thumburl = str_replace(‘.‘,‘_thumb.‘,$ori);
$imagefunc = ‘image‘ . $info[‘func‘];
if($imagefunc($small,$thumburl)) {
return str_replace(ROOT,‘‘,$thumburl);
} else {
return false;
}
}
static public function getinfo($ori) {
$arr = getimagesize($ori);
// 如果原始圖片分析不出來,直接false
if($arr === false) {
return false;
}
$info = array();
$info[‘width‘] = $arr[0];
$info[‘height‘] = $arr[1];
switch($arr[2]) {
case 1:
$info[‘func‘] = ‘gif‘;
break;
case 2:
$info[‘func‘] = ‘jpeg‘;
break;
case 3:
$info[‘func‘] = ‘png‘;
break;
case 6:
$info[‘func‘] = ‘wbmp‘;
break;
default:
$info[‘func‘] = false;
}
return $info;
}
}
image::chkcode();
?>