首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

《PHP 編程最快明白》第七講:圖片驗證碼生成與縮略圖類實作

     編輯:PHP 綜合知識

圖片驗證碼核心代碼

// 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()
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved