圖片驗證碼核心代碼
// header("Content-Type: image/png");
$code = '1234'; // 實際應用用 mt_rand 產生並存入 Session
$w = 60; $h = 18;
$im = imagecreate($w, $h);
imagecolorallocate($im, 240, 240, 240); // 背景色
for ($i=0; $i
中文驗證碼需求
- 需 TrueType 字體檔(.ttf)
- 使用
imagettftext() 替代 imagestring()
- 字串編碼轉 UTF-8:
iconv()
縮略圖類:SimpleImage(支援等比縮放、指定寬/高、百分比)
class SimpleImage {
private $image, $image_type;
public function load($filename) {
$info = getimagesize($filename);
$this->image_type = $info[2];
switch ($this->image_type) {
case IMAGETYPE_JPEG: $this->image = imagecreatefromjpeg($filename); break;
case IMAGETYPE_GIF: $this->image = imagecreatefromgif($filename); break;
case IMAGETYPE_PNG: $this->image = imagecreatefrompng($filename); break;
}
}
public function save($filename, $type=IMAGETYPE_JPEG, $quality=75, $perms=null) {
switch ($type) {
case IMAGETYPE_JPEG: imagejpeg($this->image, $filename, $quality); break;
case IMAGETYPE_GIF: imagegif($this->image, $filename); break;
case IMAGETYPE_PNG: imagepng($this->image, $filename); break;
}
if ($perms) chmod($filename, $perms);
}
public function getWidth() { return imagesx($this->image); }
public function getHeight() { return imagesy($this->image); }
public function resizeToWidth($w) { $this->resize($w, $this->getHeight() * $w / $this->getWidth()); }
public function resizeToHeight($h) { $this->resize($this->getWidth() * $h / $this->getHeight(), $h); }
public function scale($pct) { $this->resize($this->getWidth()*$pct/100, $this->getHeight()*$pct/100); }
private function resize($w, $h) {
$new = imagecreatetruecolor($w, $h);
imagecopyresampled($new, $this->image, 0,0,0,0, $w,$h, $this->getWidth(), $this->getHeight());
$this->image = $new;
}
}
// 使用範例
$img = new SimpleImage();
$img->load($_FILES['avatar']['tmp_name']);
$img->resizeToWidth(80);
$img->save(UPLOAD_DIR . "/icons/" . md5($_SESSION['user']->email) . ".jpg");
關鍵函式對照
| 功能 | 函式 |
| 建立空畫布 | imagecreate() / imagecreatetruecolor() |
| 從檔案載入 | imagecreatefromjpeg/gif/png/webp() |
| 繪文字 | imagestring() / imagettftext() |
| 畫像素/線/形狀 | imagesetpixel() / imageline() / imagefilledrectangle() |
| 高品質縮放 | imagecopyresampled() |
| 輸出/儲存 | imagejpeg/gif/png/webp() |
| 釋放記憶體 | imagedestroy() |