首页 > 解决方案 > Codeigniter:调整多张上传图片的大小只会调整一张图片的大小

问题描述

我正在尝试调整从表单上传的所有上传图像的大小,并将调整大小的副本保存在另一个文件夹中。此方法适用于单张图片上传而不是多张图片上传。这里的问题是我只调整了 1 张图像的大小。这是上传和调整大小的代码:

$this->load->library('upload');
$dataInfo = array();
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++)
    {
      $_FILES['userfile']['name']= $files['userfile']['name'][$i];
      $_FILES['userfile']['type']= $files['userfile']['type'][$i];
      $_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
      $_FILES['userfile']['error']= $files['userfile']['error'][$i];
      $_FILES['userfile']['size']= $files['userfile']['size'][$i];

      $config = array();
      $config['upload_path'] = realpath(APPPATH . '../images/myfolder/');
      $config['allowed_types'] = 'gif|jpg|png';
      $config['max_size']      = '2000';
      $config['overwrite']     = FALSE;
      $rand_string = $this->generateRandomString(3);
      $ext = strtolower(pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION));
      $filename = round(microtime(true) * 1000).$rand_string.'.'.$ext;
      $config['file_name']  = $filename;

      $this->upload->initialize($config);
      if ($this->upload->do_upload('userfile')) {
          $this->resizeImage($filename);
          $dataInfo[] = $this->upload->data();
      }
  }

调整大小功能

public function resizeImage($filename)

{
    $source_path = realpath(APPPATH . '../images/myfolder/'.$filename) ;

    $target_path = realpath(APPPATH . '../images/myfolder/thumbs/') ;

    $config_manip = array(
        'image_library' => 'gd2',
        'source_image' => $source_path,
        'new_image' => $target_path,
        'maintain_ratio' => TRUE,
        'create_thumb' => TRUE,
        'thumb_marker' => '',
        'width' => 200,
        'height' => 200
    );

    $this->load->library('image_lib', $config_manip);

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

    $this->image_lib->clear();
}

但是我只得到了 1 个图像调整大小,尽管所有图像都上传了,而不仅仅是一个。为什么会发生这种情况以及如何解决我?

标签: codeigniterimage-resizing

解决方案


假设你所有的图片都被上传了(是这样吗?)那么我建议尝试:$this->upload->initialize($config, true);和:

$this->load->library('image_lib');
$this->image_lib->initialize($config_manip);
    if (!$this->image_lib->resize()) {
        echo $this->image_lib->display_errors();
        exit;
    }

推荐阅读