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

CodeIgniter 圖像處理庫封裝:縮略圖、水印、旋轉、上傳一站式實現

     編輯:PHP 綜合知識

核心類庫封裝

在 application/libraries/Image_handler.php 中統一封裝:

class Image_handler {
    protected $ci;

    public function __construct() {
        $this->ci =& get_instance();
        $this->ci->load->library('image_lib');
    }

    /** 生成縮略圖 */
    public function create_thumb($path, $width = 80, $height = 80) {
        $config = [
            'image_library' => 'gd2',
            'source_image' => $path,
            'create_thumb' => TRUE,
            'maintain_ratio' => TRUE,
            'width' => $width,
            'height' => $height,
        ];
        $this->ci->image_lib->initialize($config);
        return $this->ci->image_lib->resize();
    }

    /** 文字水印 */
    public function add_text_watermark($path, $text = 'Copyright') {
        $config = [
            'image_library' => 'gd2',
            'source_image' => $path,
            'wm_text' => $text,
            'wm_type' => 'text',
            'wm_font_size' => 16,
            'wm_font_color' => 'ff0000',
            'wm_vrt_alignment' => 'bottom',
            'wm_hor_alignment' => 'center',
            'wm_padding' => 20,
        ];
        $this->ci->image_lib->initialize($config);
        return $this->ci->image_lib->watermark();
    }

    /** 圖片水印 */
    public function add_image_watermark($path, $watermark_path) {
        $config = [
            'image_library' => 'gd2',
            'source_image' => $path,
            'wm_type' => 'overlay',
            'wm_overlay_path' => $watermark_path,
            'wm_opacity' => 50,
            'wm_vrt_alignment' => 'bottom',
            'wm_hor_alignment' => 'right',
        ];
        $this->ci->image_lib->initialize($config);
        return $this->ci->image_lib->watermark();
    }

    /** 旋轉/翻轉 */
    public function rotate($path, $angle = 'vrt') {
        // angle: '90', '180', '270', 'vrt', 'hor'
        $config = [
            'image_library' => 'gd2',
            'source_image' => $path,
            'rotation_angle' => $angle,
        ];
        $this->ci->image_lib->initialize($config);
        return $this->ci->image_lib->rotate();
    }
}

控制器整合上傳與處理流程

public function upload() {
    $this->load->library('image_handler');

    // 1. 配置上傳
    $config = [
        'upload_path' => './public/uploads/',
        'allowed_types' => 'jpg|jpeg|png|gif',
        'max_size' => 2048,
        'file_name' => date('YmdHis') . '_' . rand(1000, 9999),
    ];
    $this->load->library('upload', $config);

    if (!$this->upload->do_upload('image')) {
        return $this->output->set_status(400)->set_output(json_encode(['error' => $this->upload->display_errors()]));
    }

    $info = $this->upload->data();
    $full_path = $info['full_path'];

    // 2. 批量處理
    $this->image_handler->create_thumb($full_path, 200, 200);
    $this->image_handler->add_text_watermark($full_path, '© MySite');
    // $this->image_handler->rotate($full_path, '90'); // 可選

    // 3. 返回結果
    $thumb_name = pathinfo($info['file_name'], PATHINFO_FILENAME) . '_thumb' . $info['file_ext'];
    echo json_encode([
        'status' => 1,
        'original' => base_url("public/uploads/{$info['file_name']}"),
        'thumb' => base_url("public/uploads/{$thumb_name}"),
    ]);
}

前端 AJAX 上傳示例

<form id="uploadForm" enctype="multipart/form-data">
    <input type="file" name="image" id="image" accept="image/*" required>
    <button type="submit">上傳並處理</button>
</form>
<div id="preview"></div>

<script>
$('#uploadForm').on('submit', function(e) {
    e.preventDefault();
    var formData = new FormData(this);
    $.ajax({
        url: '',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(res) {
            if (res.status) {
                $('#preview').html('<img src="' + res.thumb + '" alt="縮略圖"><br><img src="' + res.original + '" alt="原圖">');
            } else {
                alert('上傳失敗:' + res.error);
            }
        }
    });
});
</script>

關鍵配置提示

  • maintain_ratio = TRUE 保持縱橫比,生成的縮略圖不會變形。
  • 水印字體路徑 wm_font_path 若不指定,GD 會使用內置字體(僅支持 ASCII),中文水印需指定 TTF 字體文件路徑。
  • 上傳目錄需可寫權限(Linux: chmod 755 或 chown www-data)。
  • 大文件處理建議調整 php.ini:upload_max_filesize、post_max_size、memory_limit。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved