[CodeIgniter] 多檔上傳圖片並縮圖

Standard

用 CodeIgniter 做多檔上傳圖片,並希望同時縮圖(一大一小),並新增至資料表中。
官方討論區參考了一些寫法 .. 有空再把它優化一下,先記著寫法。

View 的表單,除了 form 記得用 enctype="multipart/form-data" 外,檔案上傳的 code 可以這樣下:

<input type="file" name="userfile1" /><br />
<input type="file" name="userfile2" /><br />
<input type="file" name="userfile3" /><br />
<input type="file" name="userfile4" /><br />
<input type="file" name="userfile5" /><br />

下面這段依需求放置在 Controller 裡:

$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|jpeg|gif|png';
$config['overwrite'] = false;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);

foreach($_FILES as $key => $value) {
  if (!empty($value['name'])) {
    if (!$this->upload->do_upload($key)) {
      $data["error"] = $this->upload->display_errors();
      $this->load->model('Photo_model');
      $data["photo"] = $this->Photo_model->getPhotoList();
      $this->template->write_view('content', 'photoAdd', $data);
      $this->template->render();
    } else {
      $fInfo = $this->upload->data();
      $this->_createThumbnail($fInfo['full_path'], FALSE, "", 330, 480);
      $this->_createThumbnail($fInfo['full_path'], TRUE, "_tn", 110, 160);
      $this->validation->set_error_delimiters('', '<br />');
      $rules['status'] = "required|integer|max_length[1]";
      $this->validation->set_rules($rules);
      $fields['status'] = "Status";
      $this->validation->set_fields($fields);

      if ($this->validation->run() == FALSE) {
        $this->photoAdd();
      } else {
        $this->load->model('Photo_model');
        $this->Photo_model->savePhoto("add");
      }
    }
  }
}

裡面有用到一個縮圖 function:

function _createThumbnail($fileName, $isThumb, $thumbMarker="", $width, $height) {
  // settings
  $config['image_library'] = 'gd2';
  $config['source_image'] = $fileName;
  $config['create_thumb'] = $isThumb;
  $config['maintain_ratio'] = TRUE;
  $config['master_dim'] = 'width';

  if(isset($thumbMarker) && $thumbMarker!=""){
    $config['thumb_marker'] = $thumbMarker;
  }

  $config['width'] = $width;
  $config['height'] = $height;

  $this->load->library('image_lib', $config);
  $this->image_lib->clear();
  $this->image_lib->initialize($config);

  if(!$this->image_lib->resize()) echo $this->image_lib->display_errors();
}

然後因為上傳送出之後也會將紀錄新增至資料表中,所以 Model 取得上傳處理過的檔名可以這樣做:

$thumb_img = substr($this->upload->file_name, 0, -4)."_tn".$this->upload->file_ext;
$large_img = substr($this->upload->file_name, 0, -4).$this->upload->file_ext;

One thought on “[CodeIgniter] 多檔上傳圖片並縮圖

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *